我有一个数据帧列表,我想遍历列表中每个数据帧的列,以使用c ++代码创建新变量(因为我正在学习Rcpp)。
输入内容如下:
$`df1`
a b c
5 30 2
4 2 15
3 2 17
$df2
a b c
5 30 2
4 2 15
3 2 17
理想情况下,输出为:
$`df1`
a b c
5.02 30.02 2
4.15 2.15 15
3.17 2.17 17
$df2
a b c
5.02 30.02 2
4.15 2.15 15
3.17 2.17 17
之后我想删除列c,但是现在我正在尝试找出执行此操作的c ++代码。
注意:我希望C列第1行中的2粘贴时为02,而不是20(因此它们的宽度相同且准确)。
答案 0 :(得分:2)
我不确定您到底想做什么,但是这里有一些快速而肮脏的代码可以循环显示数据帧列表中的列:
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::List listDf(Rcpp::List l) {
for (int i = 0; i < l.length(); ++i) {
Rcpp::DataFrame df = Rcpp::as<Rcpp::DataFrame>(l[i]);
for (int j = 0; j < df.cols(); ++j) {
Rcpp::NumericVector col = df[j];
df[j] = 1.23 * col;
}
}
return l;
}
/*** R
set.seed(42)
df1 <- data.frame(a = sample(1:100, 3),
b = sample(1:100, 3),
c = sample(1:100, 3))
df2 <- data.frame(a = sample(1:100, 3),
b = sample(1:100, 3),
c = sample(1:100, 3))
l <- list(df1 = df1, df2 = df2)
listDf(l)
*/
如果您确实想将最后一列的1/100添加到其他列,则可以使用:
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::List listDf(Rcpp::List l) {
for (int i = 0; i < l.length(); ++i) {
Rcpp::DataFrame df = Rcpp::as<Rcpp::DataFrame>(l[i]);
Rcpp::NumericVector last = df[df.cols() - 1];
for (int j = 0; j < df.cols() - 1; ++j) {
Rcpp::NumericVector col = df[j];
df[j] = col + last / 100.0;
}
}
return l;
}
/*** R
set.seed(42)
df1 <- data.frame(a = sample(1:100, 3),
b = sample(1:100, 3),
c = sample(0:99, 3))
df2 <- data.frame(a = sample(1:100, 3),
b = sample(1:100, 3),
c = sample(0:99, 3))
l <- list(df1 = df1, df2 = df2)
listDf(l)
*/
输出:
> listDf(l)
$df1
a b c
1 92.73 84.73 73
2 93.13 64.13 13
3 29.64 51.64 64
$df2
a b c
1 71.94 94.94 94
2 46.96 26.96 96
3 100.11 46.11 11
答案 1 :(得分:0)
@Ralf Stubner认为我可以为您提供视觉效果
df1 <- data.frame(a = sample(1:100, 3), b = sample(1:100, 3), c = sample(0:99, 3))
提供(未设置种子):
df1
a b c
28 70 70
14 63 5
8 12 20
dsets<-do.call("list", replicate(10, df1, simplify=FALSE)) #to replicate this 10 times
#and store as list
运行此
listDf(dsets)
输出如下:
[[9]]
a b c
35.0 77.0 70
14.5 63.5 5
10.0 14.0 20
[[10]]
a b c
35.0 77.0 70
14.5 63.5 5
10.0 14.0 20
可能我缺少一些简单的东西?