我正在尝试编写一个函数,允许我(A)创建一个以函数中的参数命名的data.frame
。 (B)此data.frame
必须是较大data.frame
(此处为df
)的子集。最后,我需要能够将对象/ data.frame
作为可打印的(等)data.frame
保存在函数之外。
一个例子是......
Group <- c("Primary Group","Primary Group","Primary Group","Primary Group","Primary Group","Primary Group","Secondary Group","Secondary Group","Secondary Group","Secondary Group","Secondary Group","Secondary Group","Tertiary Group","Tertiary Group","Tertiary Group","Tertiary Group","Tertiary Group","Tertiary Group")
Day <- c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3)
Type <- c("A","A","A","B","B","B","A","A","A","B","B","B","A","A","A","B","B","B")
Value <- c(7,3,10,3,9,4,0,9,3,10,1,6,3,4,10,2,3,1)
df<-as.data.frame(cbind(Group,Day,Type,Value))
Test_Function <- function(Group_Name, Type_Name){
paste(Group_Name,Type_Name) <- df[(df$Group == Group_Name] & (df$Type == Type_Name),]
}
理想地
Test_Function("Secondary Group","A")
只会在已保存的可用data.frame
名"Secondary Group A"
中返回第7-9行。
谢谢!任何帮助都会很棒。
答案 0 :(得分:0)
你可以这样做。
Test_Function <- function(df, Group_Name, Type_Name) {
return(subset(df, Group == Group_Name & Type == Type_Name))
}
Secondary_Group_A <- Test_Function(df, "Secondary Group", "A");
Secondary_Group_A;
# Group Day Type Value
#7 Secondary Group 1 A 0
#8 Secondary Group 2 A 9
#9 Secondary Group 3 A 3
一些评论:
df
作为Test_Function
的函数参数;否则df
Test_Function
必须是全局变量。subset
来过滤行;或者使用df[df$Group == Group_Name & df$Type == Type_Name, ]
。data.frame
的{{1}}返回对象;这里的返回对象是Test_Function
。答案 1 :(得分:0)
您的数据集存在一个问题。您的主要组值由两个单独的单词组成。然后,它不会为命名对象(据我所知)
工作然后,如果您更改名称然后生成一个单词(我在下面显示,但只更改示例中的第一个,我认为您有更长的数据集,因此您可能必须在R中执行此操作)
Group <- c("Primary_Group","Primary_Group","Primary_Group","Primary_Group","Primary_Group","Primary_Group","Secondary Group","Secondary Group","Secondary Group","Secondary Group","Secondary Group","Secondary Group","Tertiary Group","Tertiary Group","Tertiary Group","Tertiary Group","Tertiary Group","Tertiary Group")
Day <- c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3)
Type <- c("A","A","A","B","B","B","A","A","A","B","B","B","A","A","A","B","B","B")
Value <- c(7,3,10,3,9,4,0,9,3,10,1,6,3,4,10,2,3,1)
df<-as.data.frame(cbind(Group,Day,Type,Value))
然后以下功能将完成这项工作:
SelFun <- function(Data, Group,Type){
df <- Data[Data$Group== Group & Data$Type== Type, ]
assign(paste(Group,Type,sep = ''), df, envir = parent.frame())
}
示例:
SelFun(df, 'Primary_Group', 'A')
将创建一个名为Primary_GroupA的data.frame,它将包含选定的行
> Primary_GroupA
Group Day Type Value
1 Primary_Group 1 A 7
2 Primary_Group 2 A 3
3 Primary_Group 3 A 10