I would like to subset the df
columns based on sum of rows.
df
dataframe:
NE001 NE002 NE003 NE004
2 0 0 2
My expected output dfo
:
NE001 NE004
2 2
I have tried dfo <- df[,which(names(df) == colSums(df==2))]
but do not work.
Some ideas?
Are you just trying to subset the columns that sum to 2? If so, you were close. Here's an example with a small data frame.
(d <- data.frame(x = c(2, 0), y = c(1, 2), z = c(1, 1)))
# x y z
# 1 2 1 1
# 2 0 2 1
Since colSums(d) == 2
returns a logical vector, we can subset with that and the columns that are TRUE
will be returned
colSums(d) == 2
# x y z
# TRUE FALSE TRUE
d[colSums(d) == 2]
# x z
# 1 2 1
# 2 0 1
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.