Reputation: 33
I have following data object. object name is seoul1
V3 V4 V5 V6 V7 V8 V9
531 789 894 1,447 1,202 1,186 501
typeof = list, class = data.frame
I want to convert these data to atomic vecter consisting of integer or double
I used 'for' code
for(i in 1:7){
h[i]<-as.numeric(seoul1[2,][[i]])
}
but result is as below
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
why this error happen to, I don't know
Upvotes: 3
Views: 9811
Reputation: 887153
We can use unlist
to create a vector
, then convert to numeric
after removing the ,
.
as.numeric(sub(",", "", unlist(seoul1[2,], use.names=FALSE)))
#[1] 531 789 894 1447 1202 1186 501
In the OP's example dataset, there are elements like l,447, 1,202, 1,186
which will be 'character' elements and when we convert to 'numeric' with as.numeric
, it will coerce to NA because of the ,
. There is no error
message. It is a friendly warning
Remove the ,
with sub
and then do the as.numeric
.
NOTE: If there are multiple ,
within an element use gsub
instead of sub
Upvotes: 4