Writing Functions With a “data” Argument

后端 未结 2 1609
陌清茗
陌清茗 2021-01-23 23:46

I want to write a function that can take columns within a data frame or column names and the data frame they come from as arguments.

df <- data.frame(x = c(1:         


        
2条回答
  •  执念已碎
    2021-01-24 00:49

    The problem is that when calling my_fxn(x, y, z, df) the object x is not defined. Hence df$x does not return column x but NA.

    Consider this small example:

    df <- data.frame(x = 1:3, y = 4:6)
    x <- "y"
    df$x # returns column x
    [1] 1 2 3
    df[,x] #returns column y since the value which is stored in x is "y"
    [1] 4 5 6
    

    To circumvent your problem you can use data[, aaa] instead of data$aaa. Yet another alternative would be to use the dplyr package where you can use select(data, aaa).

提交回复
热议问题