我在使用 reshape 转换经典输入数据时遇到问题
我的输入数据:
df <- read.table(textConnection(" Ville POP1999 POP2010 PARC1999 PARC2010
1 Paris 1800000 2200000 150 253
2 Itxassou 1000 1800 0 NA
"))
结果是这个 data.frame :
Ville POP1999 POP2010 PARC1999 PARC2010
1 Paris 1800000 2200000 150 253
2 Itxassou 1000 1800 0 NA
我有这种类型的输入,我想使用 colsplit(reshape2 包)和正则表达式来切割我的数据框,如下所示:
Ville Date Population Parc
1 Paris 1999 1800000 150
2 Paris 2010 2200000 253
3 Itxassou 1999 1000 0
4 Itxassou 2010 1800 NA
你认为有可能用 reshape 1 或 2 和 colsplit 函数在一行中做到这一点吗?
我的 id 等于“Ville”+“Date”,所以我认为很难先用 colsplit 切割,然后再用 meld 重新使用结果 id 列:/
你有答案的想法吗?
更新 1:
我给这个问题增加了一些难度,想象一下现在我们有数千列,并且列是混合的。我尝试使用 grep 和 reshape,但此时没有结果..(请参阅@kohske 的评论很好的答案)
更新 2:
@kohske 通过添加此代码解决问题:
cn <- grep("*[0-9]",names(df),value="TRUE")
reshape(df, varying = cn, direction = "long", sep = "")