Reputation: 627
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:
V1870 V107 V1315 V1867 V1544 V1207 V1252 V1765 V342 V429 V1826 V865 V1374
4460 0 0 3 0 5 0 2 0 4 0 0 0 0
The problem is that I need to convert this row to a simple vector ( meaning I should get rid of all the column/row names) so that I can pass it to another function. I would like to be able to have the following result:
[1] 0 0 3 0 5 0 2 0 4 0 0 0 0
I tried as.list
and as.vector
, but none of them gave the results I was expecting. Any idea?
Upvotes: 5
Views: 9184
Reputation: 15458
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)
Upvotes: 6
Reputation: 13122
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
Upvotes: 1