如何在for循环中引用变量? [英] How to reference a variable in a for loop?

查看:112
本文介绍了如何在for循环中引用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历不同的data.tables和data.table中的变量.但是我在引用 for 循环

I am looping through different data.tables and the variables in the data.table. But I'm having trouble referencing the variables inside of the for loop

dt1 <- data.table(a1 = c(1,2,3), a2 = c(4,5,2))
dt2 <- data.table(a1 = c(1,43,1), a2 = c(52,4,1))

对于每个数据表,我想查找每个变量的平均值,以便观察该变量!=1.下面是我的尝试不起作用:

For each datatable, I want to find the average of each variable for observations where that variable != 1. Below is my attempt which doesn't work:

dtname = 'dt'
ind  = c('1', '2')
for (d in ind) {
  df <- get(paste0('dt', d, sep=''))
  for (v in ind) {
    varname <- paste0('a', v, sep='')
    df1 <- df %>%
      filter(varname!=1) %>%
      summarise(varname = mean(varname))
    print(df1)
    }
   }

所需的输出是获取并打印dt1中a1 = c(2,3)的平均值,dt1中a2 =(4,5,2)的平均值,a1 = c(43)的平均值dt2,dt2中a2的平均值= c(54,4).

The desired output is to take and print the average of a1 = c(2,3) in dt1, the average of a2 = (4,5,2) in dt1, the average of a1 = c(43) in dt2, the average of a2 = c(54,4) in dt2.

我在这里做错了什么?通常,我应该如何在 for 循环(变量名)内引用一个变量,该变量通过使用循环索引(v)和其他东西拼凑在一起?

What am I doing wrong here? In general, how should I reference a variable inside of a for loop (varname) that is pieced together by using the looping index (v) and something else?

推荐答案

对于纯粹的 data.table 方式,我将组合不同的 data.tables 并计算平均:

For a purely data.table way, I would combine the different data.tables and compute the averages:

# Concatenate the data.tables: 
all_dt <- rbind("dt1" = dt1, "dt2" = dt2, idcol = "origin")
all_dt
#    origin a1 a2
# 1:    dt1  1  4
# 2:    dt1  2  5
# 3:    dt1  3  2
# 4:    dt2  1 52
# 5:    dt2 43  4
# 6:    dt2  1  1

# Melt so that "a1" and "a2" are labels in a group column:
all_dt <- melt(all_dt, id.vars="origin")
all_dt
#     origin variable value
#  1:    dt1       a1     1
#  2:    dt1       a1     2
#  3:    dt1       a1     3
#  4:    dt2       a1     1
#  5:    dt2       a1    43
#  6:    dt2       a1     1
#  7:    dt1       a2     4
#  8:    dt1       a2     5
#  9:    dt1       a2     2
# 10:    dt2       a2    52
# 11:    dt2       a2     4
# 12:    dt2       a2     1

# Compute averages by each data.table and column group, ignoring 1s:
all_dt[value != 1, .(mean = mean(value)), by = .(origin, variable)]
#    origin variable      mean
# 1:    dt1       a1  2.500000
# 2:    dt2       a1 43.000000
# 3:    dt1       a2  3.666667
# 4:    dt2       a2 28.000000

这篇关于如何在for循环中引用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆