简体   繁体   中英

Subset set a dataframe column based on first row value in R

I have a 1 row dataframe called ff.

A   B   C   D   E   F
2   5   9   1   7   6

How do I create a single column dataframe (ColContribs) when the a column equals 7

E
7

Like that..? I was using

ColContribs <- ff[,ff[1,]==7]

but i'm getting this error

Error in Ops.data.frame(ff[1, ], ColContribs) : 
‘==’ only defined for equally-sized data frames

Paul

I tried to create a similar case and it worked as below.

library(tidyverse)

a <- 2
e <- 7

lol <- cbind(a,e) %>% data.frame() 

ColContribs <- lol[,lol[1,]==7] %>% data.frame()
ff <- data.frame(A = 2, B = 5, C = 9, D = 1, E = 7, F = 6)

ColContribs <- ff[,ff[1,] == 7, drop = FALSE]

Because it's a single element data frame, you need to specify drop == FALSE

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.

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