【问题标题】:Local variables inside R function doesn't workR函数内的局部变量不起作用
【发布时间】:2018-01-26 06:30:18
【问题描述】:

我需要你的帮助。我有一个如下所示的数据框

   id      home_1     home_2      home_3
1   1 -0.07288651 -1.0946734  0.06310788
2   2  0.27480575 -0.5939264 -0.10267407
3   3 -1.29267610 -1.0765848 -0.96190129
4   4 -0.53468273  0.5315489 -1.36055340
...

我想创建 3 个数据框; df1df2df3

  • df1 将有一个带有 sorted 列“home_1”的表
  • df2 将有一个带有 sorted 列“home_2”的表
  • df3 将有一个带有 sorted 列“home_3”的表

请在下面找到代码

dummy <- data.frame(id = 1:10,home_1 = rnorm(10),home_2 = rnorm(10),home_3 = rnorm(10))

f <- function(df,param1, param2) {
    c <- paste0(param1, "_", param2);
    print(paste0("Let's sort column ", c))
    df %>% arrange(c) %>% print()  #sort dataframe by column 'home_1/2/3'
}

for (i in 1:3) {
    print(paste0("Index : ",i))
    table <- paste0("df",i)     
    table <- f(dummy,"home",i) # create dataframe with name df1/2/3
}

问题 1 然后我运行我的代码,该函数无法检测到相应的列。我的函数内部的错误

Error in grouped_df_impl(data, unname(vars), drop) : 
Column `c` is unknown 

局部变量c确实存在,但group_by函数无法检测到c

有人知道如何使 列 'c' 被 group_by 函数检测到吗?

问题 2 我的 for 循环也有同样的问题。我想创建一个动态的数据框名称。

但是,以下函数 table 创建了一个名为 'table' 而不是 的数据框'df1'.

谁能告诉我如何解决这些问题? 提前谢谢你。

【问题讨论】:

  • df1&lt;- df[order(df$home_1),] df2&lt;- df[order(df$home_2),] df3&lt;- df[order(df$home_3),] 我想这样的解决方案不会让你满意吧?
  • @Adamm 不,先生,我希望函数是动态的。因为我要使用该函数创建超过 50 多个数据框。
  • 啊,当然,所以 chinsoon12 的解决方案应该可以解决问题,除非您希望每个 df(已经排序)在单独的变量中。在lapply() 之后,您有 df 的列表。但是,您可以按索引访问列表中 df 的每一行和每一列。

标签: r function local-variables


【解决方案1】:

我会为此使用 tidyverse 的排列功能,这非常简单。

我还会使用 base-r 中的“assign”来为名字存储在字符串中的 vetor 分配一个值。

library(tidyverse)
for(i in 1:(ncol(dummy)-1)){
  #define the name for the new data
  new = paste0("df",i) 

  #define the same of the column to sort on
  col = paste("home",i,sep="_") 

  # based on the data dummy, arrange the rows according to "col"
  # we need to use "get" because arrange expects bare (unquoted) column names
  tmp = dummy %>% arrange(get(col))
  assign(new, tmp)
 }

【讨论】:

    【解决方案2】:

    您可以遍历列列表,然后按每列排序

    cols <- structure(setdiff(names(dat), "id"), names=setdiff(names(dat), "id"))
    lapply(cols, function(x) dat[order(dat[,x]),])
    

    数据:

    dat <- read.table(text="id      home_1     home_2      home_3
    1 -0.07288651 -1.0946734  0.06310788
    2  0.27480575 -0.5939264 -0.10267407
    3 -1.29267610 -1.0765848 -0.96190129
    4 -0.53468273  0.5315489 -1.36055340", header=TRUE)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      相关资源
      最近更新 更多