1

I want to define the first two columns of a data frame as rownames. Actually I want to do some calculations and the data frame has to be numeric for that.

data.frame <- data_frame(id=c("A1","B2"),name=c("julia","daniel"),BMI=c("20","49"))

The values for BMI are numerical (proved with is.numeric), but the over all data.frame not. How to define the first two columns (id and name) as rownames? Thank you in advance for any suggestions

aynber
  • 22,380
  • 8
  • 50
  • 63
takeITeasy
  • 350
  • 3
  • 19

2 Answers2

2

You can combine id and name column and then assign rownames

data.frame %>%
  tidyr::unite(rowname, id, name) %>%
  tibble::column_to_rownames()

#          BMI
#A1_julia   20
#B2_daniel  49

In base R, you can do the same in steps as

data.frame <- as.data.frame(data.frame)
rownames(data.frame) <- paste(data.frame$id, data.frame$name, sep = "_")
data.frame[c('id', 'name')] <- NULL
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

Not sure if the code and result below is the thing you are after:

dfout <- `rownames<-`(data.frame(BMI = as.numeric(df$BMI)),paste(df$id,df$name))

such that

> dfout
          BMI
A1 julia   20
B2 daniel  49

DATA

df <- structure(list(id = structure(1:2, .Label = c("A1", "B2"), class = "factor"), 
    name = structure(2:1, .Label = c("daniel", "julia"), class = "factor"), 
    BMI = structure(1:2, .Label = c("20", "49"), class = "factor")), class = "data.frame", row.names = c(NA, 
-2L))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • Then this occurs: Error in df[3] : object of type 'closure' is not subsettable – takeITeasy Feb 04 '20 at 10:51
  • @takeITeasy Did you use the `df` from my answer? Also, I updated my answer so you can try it again – ThomasIsCoding Feb 04 '20 at 10:54
  • actually my real dataset is much bigger than the example I posted in the question. Is there any way to do it without having to type in everything manually? But I really thank you for your answer ;) – takeITeasy Feb 04 '20 at 11:05