问题
I want to check every row in data frame. I need to check all columns in that row to see if it contains a 1, if it does I want to populate another column that summarizes if any of the columns had a 1 or not.
So far I have tried using grepl to return a logical index by matching the '1', and then with ifelse, change the logical vector to 'yes' or 'no'
dat1$imputed_data <- ifelse(grepl("1", imputed_columns), "yes", "no")
I have also tried
for(i in nrow(imputed_columns)){
if (any(imputed_columns[i,])==1)
{
dat1$imputed_data[i] <- "yes"
}else{
dat1$imputed_data[i] <- "no"
}
}
Both of my attemps have not worked, I think the problem with both might be the way I specify the columns to do the check in.
have:
A B C
0 0 0
0 1 1
1 0 0
0 0 0
want:
A B C imputed_data
0 0 0 no
0 1 1 yes
1 0 0 yes
0 0 0 no
Please help me figure out how to make this work.Thank you in advance.
回答1:
One of many solutions:
a1 = data.frame(A = c(0,0,1,0), B = c(0,1,0,0), C = c(0,1,0,0))
a1$imputed = apply(a1, 1, function(x) ifelse(any(x == 1), 'yes', 'no'))
A B C imputed
1 0 0 0 no
2 0 1 1 yes
3 1 0 0 yes
4 0 0 0 no
回答2:
Using:
dat$imputed <- c('no','yes')[1 + (rowSums(dat == 1) > 0)]
gives:
> dat A B C imputed 1 0 0 0 no 2 0 1 1 yes 3 1 0 0 yes 4 0 0 0 no
What this does:
rowSums(dat == 1) > 0
creates a logical vector indicating whether a row contains a1
- Adding
1
to that gives an integer vector - Which in turn can be used to create the appropriate vector of
yes
andno
values.
Used data:
dat <- structure(list(A = c(0L, 0L, 1L, 0L), B = c(0L, 1L, 0L, 0L), C = c(0L, 1L, 0L, 0L)),
.Names = c("A", "B", "C"), class = "data.frame", row.names = c(NA, -4L))
回答3:
A dplyr
way would be
a1 %>% mutate(imputed_data = ifelse(rowSums(. == 1) != 0, "yes", "no"))
来源:https://stackoverflow.com/questions/46456265/populate-a-new-column-if-a-value-is-found-in-any-column