장승호*_*장승호 3 r vector dataframe
我有以下数据对象。对象名称是seoul1
V3 V4 V5 V6 V7 V8 V9
531 789 894 1,447 1,202 1,186 501
typeof = list, class = data.frame
Run Code Online (Sandbox Code Playgroud)
我想将这些数据转换为由整数或双精度组成的原子向量
我使用了“for”代码
for(i in 1:7){
h[i]<-as.numeric(seoul1[2,][[i]])
}
Run Code Online (Sandbox Code Playgroud)
但结果如下
for(i in 1:7){
h[i]<-as.numeric(seoul1[2,][[i]])
}
Warning messages:
1: NAs introduced by coercion
2: NAs introduced by coercion
3: NAs introduced by coercion
print(h)
[1] 531 789 894 NA NA NA 501
Run Code Online (Sandbox Code Playgroud)
为什么会发生这个错误,我不知道
我们可以使用unlist创建一个,然后删除后vector转换为.numeric,
as.numeric(sub(",", "", unlist(seoul1[2,], use.names=FALSE)))
#[1] 531 789 894 1447 1202 1186 501
Run Code Online (Sandbox Code Playgroud)
在OP的示例数据集中,有一些元素l,447, 1,202, 1,186将是“字符”元素,当我们使用 转换为“数字”时as.numeric,由于,. 没有error消息。这是一个友好的warning 删除,withsub然后执行as.numeric.
,注意:如果一个元素中有多个,请使用gsub而不是sub
| 归档时间: |
|
| 查看次数: |
9336 次 |
| 最近记录: |