R: convert list of numbers from character to numeric

前端 未结 3 1015
旧巷少年郎
旧巷少年郎 2021-01-24 22:17

I have a column in my dataframe where in every cell there are one or more numbers. If there are many numbers, they are seperated with a space. Furthermore, R considers them as a

3条回答
  •  [愿得一人]
    2021-01-24 22:57

    Following my comment, here is a solution using sapply :

    sum(as.numeric(strsplit("6 310 21 20 64",' ')[[1]]))
    

    which for the column of the dataframe will give something like this:

    sapply(1:nrow(df),function(x){sum(as.numeric(strsplit(str1,' ')[[x]]))})
    # 421 421 421
    

    which could be improved in sapply(strsplit(str1,' '), function(x) sum(type.convert(x))), thanks to David Arenburg's suggestion.

提交回复
热议问题