简体   繁体   English

循环遍历列以删除 NA

[英]Looping Through Columns To Remove NA's

I am trying to transform column data to numeric and round my numbers for each column in my data frame.我正在尝试将列数据转换为数字并为我的数据框中的每一列四舍五入我的数字。 I can do this manually for each column which I originally did.我可以为我最初所做的每一列手动执行此操作。 But now I am wondering how I could loop through my data's column so I don't have to do it manually in the future.但现在我想知道如何循环遍历我的数据列,这样我以后就不必手动执行了。

An example line of manually doing it is:手动执行此操作的示例行是:

data$`Impacts` <- round(as.numeric(data$`Impacts`),2)

But for implementing the for loop, I have tried the following code:但是为了实现 for 循环,我尝试了以下代码:

data <- import(from desktop/wherever/etc.)
i <- 9
for (i in data) {
 data[c(i)] <- round(as.numeric(data[c(i)]),2)
 i <- i + 1
}

And this returns an error of:这会返回以下错误:

Error in `[.data.frame`(data, c(i)) : undefined columns selected

I tried to edit my for loop my replacing data[c(i)] with data[,c(i)] and data$[,c(i)] but neither of those fixed it.我试图编辑我的 for 循环,用data[,c(i)]data$[,c(i)] data[c(i)]这些都没有修复它。

I would have thought that the columns were defined as I go through the data starting at column 9 and increment through each column with i + 1我原以为这些列通过从第 9 列开始的数据定义为 I go 并以i + 1递增每列

Am I missing something obvious?我错过了一些明显的东西吗? Thanks谢谢

We can use lapply :我们可以使用lapply

data[] <- lapply(data, function(x) round(as.numeric(x),2))

Or using dplyr :或使用dplyr

library(dplyr)
data %>%  summarise_all(~round(as.numeric(.), 2))

If you want to round only specific columns say 1:3 , you can do如果您只想对特定列进行四舍五入1:3 ,您可以这样做

data[1:3] <- lapply(data[1:3], function(x) round(as.numeric(x),2))

and

data %>% summarise_at(1:3, ~round(as.numeric(.), 2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM