R: split string into numeric and return the mean as a new column in a data frame

后端 未结 3 1564
予麋鹿
予麋鹿 2020-12-11 08:38

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

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-11 09:16

    You could use sapply to loop through the list returned by strsplit, handling each of the list elements:

    sapply(strsplit((df$a), split=", "), function(x) mean(as.numeric(x)))
    # [1] 2.5 5.0 7.5
    

提交回复
热议问题