循环以表格形式显示数据框中的变量 [英] loop for tabulation of variables in data frame

查看:65
本文介绍了循环以表格形式显示数据框中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有n变量的df. 我想遍历变量的一个子集并生成一个频率表.

I have a df with n variables. I want to loop through a subset of the variables and produce a frequency table.

例如,下面给出df:

id a b c d 
1 0 1 0 1 
2 1 0 1 0
3 0 1 0 1

我尝试执行以下操作但未成功:

I tried to do the following without success:

varlist <- c("a", "c")

for (i in varlist){
   print(table(df$i))
               }

推荐答案

(首先,将矩阵df转换为数据框:)

(First, your matrix df is transformed to a data frame:)

df <- setNames(as.data.frame(df), letters[1:4])

$不适用于变量.您必须改为使用[[:

The $ does not work with variables. You have to use [[ instead:

for (i in varlist){
  print(table(df[[i]]))
}

但是,一个更简单的解决方案是lapply:

However, a much easier solution for your problem is lapply:

lapply(df[varlist], table)


:

主要区别是$不允许计算索引,而[[允许.

The main difference is that $ does not allow computed indices, whereas [[ does.

这篇关于循环以表格形式显示数据框中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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