Home > Net >  Extracting and pasting variables of a data.frame in R
Extracting and pasting variables of a data.frame in R

Time:03-31

I'm trying to achieve my DESIRED_OUTPUT below, inside the foo() function without success.

Is there a way for foo's output to exactly match my DESIRED_OUTPUT?

m="cyl       hp      wt    vs gear
1 6.1875 146.6875 3.21725  0    3
2 6.1875 146.6875 3.21725  1    3
3 6.1875 146.6875 3.21725  0    4
4 6.1875 146.6875 3.21725  1    4
5 6.1875 146.6875 3.21725  0    5
6 6.1875 146.6875 3.21725  1    5"
dat <- read.table(text=m,h=T) 

DESIRED_OUTPUT <- with(dat, paste(vs, gear))

# [1] "0 3" "1 3" "0 4" "1 4" "0 5" "1 5"

foo <- function(dat, nm){
  
  with(dat, paste(nm))  
  
}
# EXAMPLE OF USE:
foo(dat, c("vs","gear"))

CodePudding user response:

You could use

foo <- function(dat, nm) do.call(paste, dat[nm])

Resulting in:

foo(dat, c("vs","gear"))
#> [1] "0 3" "1 3" "0 4" "1 4" "0 5" "1 5"
  • Related