将附加到该列的属性数据复制为另一列 [英] Copying Attribute Data Attached To Column As Another Column

查看:111
本文介绍了将附加到该列的属性数据复制为另一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据集,每列都有一个存储数据的属性.意思是,列具有按行的值,然后列的属性也具有值.

I have a data set with each column having an attribute storing data. Meaning, columns has row wise values and then attributes to columns also have a value.

我可以使用attr()读取附加到列的数据作为属性.但是,我的目标是捕获这些属性值并复制为列.

I can read the data attached to the column as attribute using attr(). However, my goal is to capture these attribute values and replicate as a columns.

阅读属性

> attr(data$`column1`, "metadata")$DP.SomeNumber1
"6200"
> attr(data$`column2`, "metadata")$DP.SomeNumber2
"7200"

输入数据

column1 column2
 -0.01   0.05
 -0.01   0.05
 -0.01   0.05
 -0.01   0.05
 -0.01   0.05
 -0.01   0.05
 -0.01   0.05
 -0.01   0.05

然后使用上面的代码,我要附加如下所示的值.

Then using above code, I want to append the values as shown below.

输出数据

column1 SomeNumber1 column2 SomeNumber2
 -0.01    6200        0.05     7200
 -0.01    6200        0.05     7200
 -0.01    6200        0.05     7200
 -0.01    6200        0.05     7200
 -0.01    6200        0.05     7200
 -0.01    6200        0.05     7200
 -0.01    6200        0.05     7200
 -0.01    6200        0.05     7200

如何对超过1000列的数据进行递归实现?每次读取都需要使用唯一的列名称调用attr()来捕获属性数据,然后将其复制为另一个adjust列.

How can I implement this recursively for data with more than 1000 columns? Each read will require call to attr() with unique column name to capture the attribute data and then replicate it as another adjust column.

我对如何以一种优化的方式递归地执行此操作感到困惑.

I am getting confused on how I can recursively do this and that too in an optimized way.

请分享建议,谢谢.

推荐答案

很遗憾,您没有提供可复制的示例.所以我创建了一个,希望它能解决您的问题:

Unfortunately you didn't provide an reproducible example. so I created one and hope it fits your problem:

column1 = rep(-0.01, 8)
attr(column1, "metadata")$DP.SomeNumber1 = "6200"
column2 = rep(0.05, 8)
attr(column2, "metadata")$DP.SomeNumber2 = "7200"

data = data.frame(column1, column2)

使用lapply,您可以遍历数据框的列.对于每一列,将属性作为新列添加到原始数据框.这是我的解决方案的代码:

Using lapply you can iterate over the columns of your dataframe. For each column the attributes were added as a new column to the original dataframe. Here is the code of my solution:

# create function to extract attributes of a given column(name) an create new column in original dataframe
attr2col <- function(col) {
  myAttr = attr(data[,col], "metadata")
  data[,sub("^DP\\.", "", names(myAttr))] <<- myAttr[[names(myAttr)]]
}

# iterate over colums of original dataframe
lapply(names(data), attr2col)

这篇关于将附加到该列的属性数据复制为另一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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