Given a data frame with columns:
- "length1" integer as characters
- "length2" each element is a string of numbers
I would like to get the percentage of the length2 column with respect to the length1 column. So something like df$length2 / df$lenght1 *100. Pls see the following minimal example:
> df=data.frame(length1=c("10","12","14"))
> df$length2=list("2,3,4","4,5,3","3,2,6")
> df
length1 length2
1 10 2,3,4
2 12 4,5,3
3 14 3,2,6
> dfresult=df
> dfresult$resultInPercent=list("20,30,40","33,41,25","21,14,42")
> dfresult
length1 length2 resultInPercent
1 10 2,3,4 20,30,40
2 12 4,5,3 33,41,25
3 14 3,2,6 21,14,42
I cant get it to work, my approach was:
dfresult=apply(df, 1, function(x)
{
lapply(lapply(lapply(x$length2,strsplit,split=","),as.numeric),function(y)
{
round(as.numeric(y)/as.numeric(x$length1)*100)
}
)
}
)
Error in lapply(lapply(x$length2, strsplit, split = ","), as.numeric) : (list) object cannot be coerced to type 'double'
I gave up here and got the feeling what I do is way to complicated.