我已经搜索过高低,但我仍然坚持如何处理这个问题。我有两组列,我想逐行,但我想循环多列。如果我要手动执行此操作,我希望:
df1[1,1]+df2[1,1]
df1[2,1]+df2[2,1]
等......我找到了很多有用的例子,说明如何做:
apply(df[,c("a","d")], 1, sum)
虽然我想在很多专栏上做这件事。此外,虽然它并不完全相关,但我想将我的问题说成尽可能接近我的现实,所以下面我的例子包括NA,因为我的实际数据包含许多缺失值。
# make a data frame, df1, with three columns
a <- sample(1:100, 50, replace = T)
b <- sample(100:300, 50, replace = T)
c <- sample(2:50, 500, replace = T)
df1 <- cbind(a,b,c)
# make another data frame, df2, with three columns
x <- sample(1:100, 50, replace = T)
y <- sample(100:300, 50, replace = T)
z <- sample(2:50, 50, replace = T)
df2 <- cbind(x,y,z)
# make another data frame, df2, with three columns
x <- sample(1:100, 50, replace = T)
y <- sample(100:300, 50, replace = T)
z <- sample(2:50, 50, replace = T)
df2 <- cbind(x,y,z)
可以从http://www.r-bloggers.com/function-to-generate-a-random-data-set/
中随机抛出几个NAsNAins <- NAinsert <- function(df, prop = .1){
n <- nrow(df)
m <- ncol(df)
num.to.na <- ceiling(prop*n*m)
id <- sample(0:(m*n-1), num.to.na, replace = FALSE)
rows <- id %/% m + 1
cols <- id %% m + 1
sapply(seq(num.to.na), function(x){
df[rows[x], cols[x]] <<- NA
}
)
return(df)
}
将NA添加到帧
NAins(df1, .2)
NAins(df2, .14)
然后,我尝试沿每个数据框中的列进行seq,并使用apply将索引设置为1,意味着对每个行条目求和。这不起作用。
for(i in seq_along(df1)){
for(j in seq_along(df2)){
apply(c(df1[,i], col2[j]), 1, function(x) sum(x, na.rm = T))}}
感谢您的帮助!
答案 0 :(得分:2)
您应该只能将NA
替换为0,然后使用“+”添加:
replace(df1, is.na(df1), 0) + replace(df2, is.na(df2), 0)
# X Y Z
# 1 7 19 6
# 2 11 12 1
# 3 16 14 11
# 4 13 7 13
# 5 10 2 11
或者,如果您只有两个data.frame
,则可以list
收集它们并使用Reduce
:
Reduce("+", lapply(mget(c("df1", "df2", "df3")), function(x) replace(x, is.na(x), 0)))
以下是一些示例数据(以及我认为创建它的更简单方法):
set.seed(1) ## Set a seed so others can reproduce your sample data
dfmaker <- function() {
setNames(
data.frame(
replicate(3, sample(c(NA, 1:10), 5, TRUE), FALSE)),
c("X", "Y", "Z"))
}
df1 <- dfmaker()
df1
# X Y Z
# 1 2 9 2
# 2 4 10 1
# 3 6 7 7
# 4 9 6 4
# 5 2 NA 8
df2 <- dfmaker()
df2
# X Y Z
# 1 5 10 4
# 2 7 2 NA
# 3 10 7 4
# 4 4 1 9
# 5 8 2 3
df3 <- dfmaker()
答案 1 :(得分:0)
您可以将data.frame转换为数组,并使用apply函数对它们求和。
#include <iostream>
#include <array>
class lines_from {
public:
std::istream ∈
using value_type = std::string;
std::string operator*() {
std::string line;
std::getline(in, line);
return line;
}
bool good() const {
return in.good();
}
};
template<int N, class T>
auto take(T &range){
std::array<typename T::value_type, N> value;
for (auto &e: value) { e = *range; }
return value;
}