简体   繁体   English

在R中使用lapply

[英]using lapply in R

I have a data frame with 10 variables, which obviously has some data issues. 我有一个包含10个变量的数据框,显然有一些数据问题。 Eg, say column1 should not be greater than column2, but in the data we have some entries which violate this. 例如,说column1不应大于column2,但是在数据中我们有一些违反此规定的条目。 So, we assume that if column1>column2, replace the value in column1 with the corresponding value in column2. 因此,我们假设如果column1> column2,则将column1中的值替换为column2中的相应值。 Now I want to compare say col1,col3,col4 with col2 and apply the same logic as above to all the columns. 现在,我想将col1,col3,col4与col2进行比较,并对所有列应用与上述相同的逻辑。 I have used the ifelse function in R, like 我在R中使用过ifelse函数,例如

data$col1 <- ifelse (data$col1>data$col2,data$col2,data$col1)

this works fine. 这很好。

But is there a way by which I can achieve the same for all the cols (ie, col1,col3and col4) at once? 但是,有没有一种方法可以一次实现所有cols(即col1,col3和col4)的相同功能? I think it can be done using lapply , but not quite sure how. 我认为可以使用lapply完成此操作,但不确定如何操作。

This version sets all values in any column other than 2 to be less than or equal to values in column 2 . 此版本将除2以外的任何列中的所有值都设置为小于或等于2列中的值。 First, make toy data: 首先,制作玩具数据:

df <- as.data.frame(replicate(10, sample(1:10), simplify=F))
names(df) <- paste0("col", 1:10)

Now, use lapply to achieve your objective, replacing all columns other than 2 by the capped value: 现在,使用lapply实现您的目标,将2列以外的所有列替换为上限值:

df[-2] <- lapply(df[-2], function(x) ifelse(x > df[[2]], df[[2]], x))
df

It's not clear exactly what you're trying to do, but if you can clarify I can provide a more targeted answer. 目前尚不清楚您要做什么,但是如果您可以澄清,我可以提供更有针对性的答案。 Either way hopefully this gives you some ideas. 希望这两种方法都能给您一些想法。

You can do with a for : 您可以使用for

set.seed(31415)
(data <- data.frame(matrix(rnorm(100), ncol=10)))

for (i in c(1, 3, 4, 7)) { # Let's check columns 1, 3, 4 and 7
data[, i] <- ifelse(data[, i] > data[, 2], data[, 2], data[, i])
}
data

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

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