【发布时间】:2016-05-12 09:54:02
【问题描述】:
我有一个字符向量,格式如下:
vv<-c(1,2,"c", "2%", 3, "b", "4%") # original vector
我根据以下代码行从这个向量创建了一些新的向量:
# original vector
vv<-c(1,2,"c", "2%", 3, "b", "4%")
# vector without the characters , i.e the c and b
vv1<-vv[-grep("[a-zA-Z]", vv)]
# Steps to create the vector of "integers"
strip_percents <- as.numeric(gsub("%", "", vv1))
no_percents <- as.numeric(vv1[-grep("%", vv1)])
# Vector that collects the strings
strings_vv1 <- vv[grep("[a-zA-Z]", vv)]
# Vector the collects the percentage numbers
perce_vv1 <-vv1[grep("%", vv1)]
perce_vv1 <- as.numeric(gsub("%", "", perce_vv1))/100
我的目的是结合所有这些向量并创建一个数据框,但遵循原始向量的结构/顺序。换句话说,我想在“正确的位置”用 NA 填充数据框。因此,例如,我希望我的数据框看起来像这样:
df<-data.frame(original=vv, numerics=c(1,2,NA,0.02,3,NA,0.04), integers=c(1,2,NA,NA,3,NA,NA), characters=c(NA,NA,"c",NA,NA,"b",NA))
original numerics integers characters
1 1 1.00 1 <NA>
2 2 2.00 2 <NA>
3 c NA NA c
4 2% 0.02 NA <NA>
5 3 3.00 3 <NA>
6 b NA NA b
7 4% 0.04 NA <NA>
有人可以帮我完成这项任务吗?
【问题讨论】:
标签: r vector dataframe data-cleaning