I have data frame where each row contain one non- NA
value.
ED1 ED2 ED3 ED4 ED5
1 NA NA NA NA
NA NA 1 NA NA
NA 1 NA NA NA
NA NA NA NA 1
For each row, I want to get the index and name of the column containing the non- NA
value, ie:
Indices: c(1, 3, 2, 5)
, and their corresponding column names: c("ED1" "ED3" "ED2" "ED5")
There is no need to use an apply()
loop here. You could use max.col()
in combination with a negated call to is.na()
.
max.col(!is.na(df))
# [1] 1 3 2 5
That gives us the column numbers where the 1s are. To get the column names, we can use that in a vector subset of the names()
of the data frame.
names(df)[max.col(!is.na(df))]
# [1] "ED1" "ED3" "ED2" "ED5"
So we can get the desired data frame, with factor column, by doing
data.frame(EDU = names(df)[max.col(!is.na(df))])
# EDU
# 1 ED1
# 2 ED3
# 3 ED2
# 4 ED5
Data:
df <- structure(list(ED1 = c(1, NA, NA, NA), ED2 = c(NA, NA, 1, NA),
ED3 = c(NA, 1, NA, NA), ED4 = c(NA, NA, NA, NA), ED5 = c(NA,
NA, NA, 1)), .Names = c("ED1", "ED2", "ED3", "ED4", "ED5"
), row.names = c(NA, -4L), class = "data.frame")
df <- data.frame( ED1 = c( 1, NA, NA, NA),
ED2 = c( NA, NA, 1 , NA),
ED3 = c( NA, 1, NA, NA),
ED4 = c( NA, NA, NA, NA),
ED5 = c( NA, NA, NA, 1) )
df_new <- data.frame( EDU = as.factor(apply(df,1,which.min)) )
levels(df_new$EDU) <- paste0("ED",levels(df_new$EDU))
.
> df
ED1 ED2 ED3 ED4 ED5
1 1 NA NA NA NA
2 NA NA 1 NA NA
3 NA 1 NA NA NA
4 NA NA NA NA 1
> df_new
EDU
1 ED1
2 ED3
3 ED2
4 ED5
Another option is
v1 <- names(df)[+(!is.na(df)) %*% seq_along(df)]
v1
#[1] "ED1" "ED3" "ED2" "ED5"
data.frame(EDU=v1)
Or using pmax
names(df)[do.call(pmax, c(df *col(df), list(na.rm=TRUE)))]
#[1] "ED1" "ED3" "ED2" "ED5"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.