sample data.frame:
structure(list(a = c(1, 2, 3), b = c(4, 5, 6), c = c(7, 8, 9)), .names = c("a", "b", "c"), row.names = c(na, -3l), class = "data.frame")
output:
df # b c # 1 1 4 7 # 2 2 5 8 # 3 3 6 9
i'd first , third columns, want subset name , column index.
df[, "a"] # [1] 1 2 3 df[, 3] # [1] 7 8 9 df[, c("a", 3)] # error in `[.data.frame`(df, , c("a", 3)) : undefined columns selected df[, c(match("a", names(df)), 3)] # c # 1 1 7 # 2 2 8 # 3 3 9
are there functions or packages allow clean/simple syntax, in third example, while achieving result of fourth example?
mabe use dplyr
?
for interactive use - i.e., if know ahead of time name of column want select
library(dplyr) df %>% select(a, 3)
if not know name of column in advance, , want pass variable,
x <- names(df)[1] x [1] "a" df %>% select_(x, 3)
either way output is
# c #1 1 7 #2 2 8 #3 3 9
Comments
Post a Comment