convert a row of a data frame to a simple vector in R

后端 未结 3 1501
太阳男子
太阳男子 2020-12-20 03:23

I have a huge data frame from which I only select a couple of rows. Then I remove some of the columns based on a condition. let us say that I choose row 4460 as shown bellow

相关标签:
3条回答
  • 2020-12-20 03:40

    Example from mtcars data

    mydata<-mtcars
    k<-mydata[1,]
              mpg cyl disp  hp drat   wt  qsec vs am gear carb
    Mazda RX4  21   6  160 110  3.9 2.62 16.46  0  1    4    4
    names(k)<-NULL
    
    unlist(c(k))
     [1]  21.00   6.00 160.00 110.00   3.90   2.62  16.46   0.00   1.00   4.00   4.00
    

    Updated as per @Ananda: unlist(mydata[1, ], use.names = FALSE)

    0 讨论(0)
  • 2020-12-20 03:44

    Try to use row index.

    e.q.

    list <- yourdataframe[4460, ]
    
    0 讨论(0)
  • 2020-12-20 04:02

    I think it's already a vector, only with names in each element (inherited from the data.frame).

        #random df
        DF = data.frame(col1 = sample(1:10, 10), col2 = sample(1:10,10), col3 = sample(1:10, 10))
    
        DF[5,]
          col1 col2 col3
        5    3    7    5
    
        mode(DF[5,]) 
        [1] "list"
    
        mode(unlist(DF[5,]))
        [1] "numeric"
    
        names(DF[5,])
        [1] "col1" "col2" "col3"
    
        sum(DF[5,]) # computations are naturally done
        [1] 15
    

    To get rid of the names, nontheless, you could:

        unname(unlist(DF[5,]))
        [1] 3 7 5
    
    0 讨论(0)
提交回复
热议问题