I have a large data frame with columns that are a character string of numbers such as "1, 2, 3, 4". I wish to add a new column that is the average of these numbers. I have set up the following example:
set.seed(2015)
library(dplyr)
a<-c("1, 2, 3, 4", "2, 4, 6, 8", "3, 6, 9, 12")
df<-data.frame(a)
df$a <- as.character(df$a)
Now I can use strsplit to split the string and return the mean for a given row where the [[1]] specifies the first row.
mean(as.numeric(strsplit((df$a), split=", ")[[1]]))
[1] 2.5
The problem is when I try to do this in a data frame and reference the row number I get an error.
> df2<- df %>%
+ mutate(index = row_number(),
+ avg = mean(as.numeric(strsplit((df$a), split=", ")
[[index]])))
Error in strsplit((df$a), split = ", ")[[1:3]] :
recursive indexing failed at level 2
Can anyone explain this error and why I cannot index using a variable? If I replace index with a constant it works, it seems to not like me using a variable there.
Much thanks!
You could use
sapply
to loop through the list returned bystrsplit
, handling each of the list elements: