[英]function that outputs a data frame in R
I have an example data frame named df
: 我有一个名为df
的示例数据框:
Store Cash Only
1 "A" Y
2 "B" N
3 "C" N
4 "D" Y
I would like to create a function that allows a user to see whether or not a store is "cash only". 我想创建一个允许用户查看商店是否为“仅现金”的功能。 Ideally, the function would output only the stores that have a Y
in the Cash Only
column. 理想情况下,该函数将仅输出“仅Cash Only
列中具有Y
的商店。 The output should look like this: 输出应如下所示:
Store Cash Only
1 "A" Y
2 "D" Y
Does anyone know how I would go about this? 有人知道我会怎么做吗? Thanks! 谢谢!
you just need to write a function that returns a subset of the input dataframe where cash == "Y"
: 您只需要编写一个函数即可返回输入数据框的子集,其中cash == "Y"
:
df = data.frame(store=c("a","b","c","d"), cash=c("Y","N","N","Y"))
cash_only <- function(df){
return(subset(df, cash == "Y"))
}
new_df <- cash_only(df)
This function gives you more flexibility, 此功能为您提供更大的灵活性,
select_sub_dataframe<-function(df,colname,value){ return(df[df[,colname]==value,]) } select_sub_dataframe <-function(df,colname,value){return(df [df [,colname] == value,])}
You can call this function and get the subset by 您可以调用此函数并通过以下方式获取子集
select_sub_dataframe(df,"Cash Only","Y") select_sub_dataframe(df,“仅现金”,“ Y”)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.