R:将数字列表从字符转换为数字 [英] R: convert list of numbers from character to numeric
问题描述
我在数据帧中有一列,每个单元格中都有一个或多个数字。如果有很多数字,它们被分隔开一个空格。此外,R将它们视为字符向量。我真的想把它们转换为数字(如果可能的话,立即总结)。
例如我的单元格之一可能类似于
6 310 21 20 64
我试过了
Reduce b $ b
和
as.numeric(L)
但我总是得到
警告消息: / p>
按照我的意见,这里是一个解决方案使用 sapply
:
sum(as.numeric(strsplit 21 20 64,'')[[1]]))
dataframe会给出这样的东西:
sapply(1:nrow(df),function(x){sum(as.numeric (strsplit(str1,'')[[x]]))})
#421 421 421
$ b b
这可以在 sapply(strsplit(str1,''),function(x)sum(type.convert(x)))
Arenburg的建议。
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 character vector. I'd really like to convert them to numeric (and if possible sum them up right away). E.g. one of my cells might look like
6 310 21 20 64
I've tried
Reduce(sum,L)
and
as.numeric(L)
but I always get Warning message:
NAs introduced by coercion
Here, L is just a sample object I created to put one of my cells into.
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.
这篇关于R:将数字列表从字符转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!