从数据框中的每一列创建变量 [英] Create Variable from Each Column in Data Frame

查看:74
本文介绍了从数据框中的每一列创建变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其中包含要单独查看的列.我不确定像这样单独分析数据的通用方法是什么,但是我想为原始数据帧中的每一列创建一个单独的变量/数据帧.我知道可以子集化,但是有没有一种方法可以使用for循环(这是最简单的方法吗?)以便从数据框中的x列创建x个新变量?

I have one data frame that contains columns that I want to look at individually. I am not sure what the common method is for analyzing data individually like this, but I want to create a separate variable/data frame for each column in my original data frame. I know I can subset, but is there a way I can use a for loop (is this the easiest way?) in order to create x new variables from the x columns in my data frame?

有关我的数据框的更多详细信息,我有一个产品和一个相应的索引(该产品将根据该索引进行判断).

For more details on my data frame, I have a product and a corresponding index (which the product is being judged against).

数据帧示例:

Date         Product 1     Index 1     Product 2     Index 2
1/1/1995        2.89        2.75         4.91         5.01
2/1/1995        1.38        1.65         3.47         3.29

因此,我想为每个产品和相应的索引创建一个变量,而无需为每个产品手动创建数据框,或者在我要分析产品时不设置子集.

So I would like to create a variable for each product and corresponding index, without manually creating a data frame for each one, or subsetting when i want to analyze the product.

推荐答案

您可以为这些列建立索引,并将它们放入一个新列表,其中每个元素都包含产品/索引对和日期列.

You could index the columns and put them into a new list with each element containing the product/index pair and the date column.

ind <- seq(2, by = 2, length.out = ncol(dat[-1])/2)
(sets <- lapply(ind, function(i) dat[c(1, i:(i+1))]))
# [[1]]
#       Date Product1 Index1
# 1 1/1/1995     2.89   2.75
# 2 2/1/1995     1.38   1.65
# 
# [[2]]
#       Date Product2 Index2
# 1 1/1/1995     4.91   5.01
# 2 2/1/1995     3.47   3.29

如果需要,可以使用list2env

list2env(setNames(sets, paste0("Set", seq_along(sets))), .GlobalEnv)
Set1
#       Date Product1 Index1
# 1 1/1/1995     2.89   2.75
# 2 2/1/1995     1.38   1.65
Set2
#       Date Product2 Index2
# 1 1/1/1995     4.91   5.01
# 2 2/1/1995     3.47   3.29

数据:

dat <- 
structure(list(Date = structure(1:2, .Label = c("1/1/1995", "2/1/1995"
), class = "factor"), Product1 = c(2.89, 1.38), Index1 = c(2.75, 
1.65), Product2 = c(4.91, 3.47), Index2 = c(5.01, 3.29)), .Names = c("Date", 
"Product1", "Index1", "Product2", "Index2"), class = "data.frame", row.names = c(NA, 
-2L))

这篇关于从数据框中的每一列创建变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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