简体   繁体   中英

How to use different column names in a function in R

My data are similar to the following data:

df<-read.table(text=" degree
100
120
140
150
160",header=TRUE)

and I have this simple function

df1<-function(x){
mean(df$degree)
}
df1(df)

I get the mean. However, sometimes I want to use different names for the column name, say 'point' instead of the 'degree'. Indeed, I do not want to use 'degree' in my codes. Happy to describe should you think it is necessary.

We can pass an argument for column name

f1 <- function(dat, colNm) mean(dat[[colNm]], na.rm = TRUE)
f1(df, "degree")
#[1] 134

f1(setNames(df, "point"), "point")
#[1] 134

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