R循环用于基本数据清理



我对R和编程有点陌生。我必须清理大量数据,通常在多列中都是类似的问题。所以,我想使用一个循环,而不是写出每一行代码。我有类似的数据:

black <- c("1.33%", "9.22%", "10.71%")
white <- c("5.23%", "8.12%", "11.72%")
day <- c("Wednesday", "Thursday", "Friday")
blue <- c("2.21%", "1.12%", "8.79%")
df <- data.frame(black, white, day, blue)

这给我带来了一个这样的数据帧:

black  white       day  blue
1  1.33%  5.23% Wednesday 2.21%
2  9.22%  8.12%  Thursday 1.12%
3 10.71% 11.72%    Friday 8.79%

我读到有for循环,而且apply((家族的工作方式也类似于R中的循环。。。我该如何循环浏览黑色、白色和蓝色变量(但不是天(,以便我可以:

  • 删除%符号
  • 将类型从字符更改为数字
  • 四舍五入到小数点后1位

就像我说的,我想知道如何将其写成for循环和application。要删除我以前使用过mutate和gsub的%符号。。。

谢谢你的建议,特别是帮助我写易读的代码!最佳,罗杰

以下是使用dplyr的一种整洁方法

library(dplyr)
clean_my_data<-function(input){
gsub("%", "", input) %>% as.numeric() %>% round(1)
}
df_new<-df %>%
mutate(across(c(black,white,blue), clean_my_data))
df_new
#>   black white       day blue
#> 1   1.3   5.2 Wednesday  2.2
#> 2   9.2   8.1  Thursday  1.1
#> 3  10.7  11.7    Friday  8.8

创建于2022-01-15由reprex包(v2.0.1(

这是一种快速而肮脏的方法,而且可以改进!

首先你需要一个函数来完成这项工作,然后你应用这个函数(或者你做一个循环,这取决于你(。

clean_color <- function(x) {
# just remove the last char, it can fail on data like that "1.38% "
without_percent = substr(x, 
start = 1, 
stop = nchar(x) - 1)
# second part convert in mun and round it
round(as.numeric(without_percent),1)
}

然后你应用这个功能:

sapply(df[,c(1:2,4)], clean_color)

最新更新