Convert a row of a data frame to vector

前端 未结 6 610
予麋鹿
予麋鹿 2020-12-04 09:05

I want to create a vector out of a row of a data frame. But I don\'t want to have to row and column names. I tried several things... but had no luck.

This is my data

6条回答
  •  天命终不由人
    2020-12-04 09:16

    Note that you have to be careful if your row contains a factor. Here is an example:

    df_1 = data.frame(V1 = factor(11:15),
                      V2 = 21:25)
    df_1[1,] %>% as.numeric() # you expect 11 21 but it returns 
    [1] 1 21
    

    Here is another example (by default data.frame() converts characters to factors)

    df_2 = data.frame(V1 = letters[1:5],
                      V2 = 1:5)
    df_2[3,] %>% as.numeric() # you expect to obtain c 3 but it returns
    [1] 3 3
    df_2[3,] %>% as.character() # this won't work neither
    [1] "3" "3"
    

    To prevent this behavior, you need to take care of the factor, before extracting it:

    df_1$V1 = df_1$V1 %>% as.character() %>% as.numeric()
    df_2$V1 = df_2$V1 %>% as.character()
    df_1[1,] %>% as.numeric()
    [1] 11  21
    df_2[3,] %>% as.character()
    [1] "c" "3"
    

提交回复
热议问题