遇到将数据帧转换为R的问题
我有一堆列被读取factors并带有%符号.
我知道我可以做一个专栏:
df[,3] <- as.numeric(sub("%","",df[,3]))
Run Code Online (Sandbox Code Playgroud)
但是尝试将其应用于整个数据集似乎不起作用并将所有值更改为NA.我究竟做错了什么?这是我试图使用的代码:
df[,-1] <- as.numeric(sub("%","",df[,-1]))
Run Code Online (Sandbox Code Playgroud)
编辑:我知道我可以解决这个问题:
for (i in 2:66) {
df[,i] <- as.numeric(sub("%","",df[,i]))
print(class(df[,i]))
}
Run Code Online (Sandbox Code Playgroud)
但必须有更优雅(并且希望是单行)的方式来做到这一点.
编辑2:这是一些数据:
Year v1 v2 v3 v4
1 12-Oct 0% 0% 39% 14%
2 12-Nov 0% 6% 59% 4%
3 12-Dec 22% 0% 37% 26%
4 13-Jan 45% 0% 66% 19%
5 13-Feb 28% 39% 74% 13%
Run Code Online (Sandbox Code Playgroud)
回答:在你们帮助了我之后,我在一个命令中就是这样做的!我在指定功能部分时遇到了问题.
df=read.csv("all response rates.csv")
df[-1]<-data.frame(apply(df[-1], 2, function(x)
as.numeric(sub("%","",as.character(x)))))
Run Code Online (Sandbox Code Playgroud)
parse_number从readr包中删除%符号.对于您的给定数据集,请尝试:
library(dplyr)
library(readr)
res <- cbind(df %>% select(Year), # preserve the year column as-is
df %>% select(-Year) %>% mutate_all(funs(parse_number))
)
> res
Year v1 v2 v3 v4
1 12-Oct 0 0 39 14
2 12-Nov 0 6 59 4
3 12-Dec 22 0 37 26
4 13-Jan 45 0 66 19
5 13-Feb 28 39 74 13
Run Code Online (Sandbox Code Playgroud)
如果您不需要保留第一列,则只需要摘录:
df %>% select(-Year) %>% mutate_all(funs(parse_number))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4243 次 |
| 最近记录: |