基于R中函数的变量过滤数据和命名

时间:2018-06-05 22:44:21

标签: r

我正在尝试编写一个函数,允许我(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行。

谢谢!任何帮助都会很棒。

2 个答案:

答案 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

一些评论:

  1. 我会将df作为Test_Function的函数参数;否则df Test_Function必须是全局变量。
  2. 我们可以使用subset来过滤行;或者使用df[df$Group == Group_Name & df$Type == Type_Name, ]
  3. 您需要存储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