Reputation: 221
I'm sorry if this is elementary or a repeat question. But I have been looking for hours, to little avail.
I want to take multiple numeric columns in a dataframe (say 100), and combine them into a single numeric vector that I can store in a single column. I plan to use the dplyr::transmute() function to store the result and drop the original 100 columns. However, that is not the problem. My problem is getting the operation to iterate over each of the rows in the dataframe. To put it simply, imagine I was working with the mtcars dataframe:
as.numeric(mtcars[x,2:8])
would give me a single numeric vector of row x, columns 2 (cyl) through 8 (vs), which I could then store in a new column. But how would I apply this to all 32 rows of the data frame without typing it out 32 ways, once for each row?
(yes, I have tried the "apply" functions, but I am still learning R, so may have been unable to nail down the correct syntax)
(also, I suppose I could do it in a for loop, but have gathered that these are generally frowned upon in R)
Any help would be greatly appreciated, and please try to be gentle!
Upvotes: 1
Views: 2634
Reputation: 4513
I don't think davo1979 is looking to transform his data to a long format, therefore, I don't think tidyr::gather is the tool he wants.
The answer, which I think, most closestly address his question is
lapply(1:nrow(mtcars), function(x) as.numeric(mtcars[x,2:8]))
This will store each row as a numeric vector, contained within a list.
However, davo1979 it is important to know what is your ultimate goal with this data. I ask because your desired outcome of a bunch of numeric vectors is a clumsy way to handle and store data in R.
Upvotes: 1
Reputation: 6170
Have you tried tidyr's gather()
function? Here's an example from the documentation:
library(tidyr)
stocks <- data_frame(
time = as.Date('2009-01-01') + 0:9,
X = rnorm(10, 0, 1),
Y = rnorm(10, 0, 2),
Z = rnorm(10, 0, 4)
)
gather(stocks, stock, price, -time)
stocks %>% gather(stock, price, -time)
Upvotes: 0