我的数据框由 12 列和 n 行组成。我想检查每行的第3:10列的值。如果值 1 ,我想计算一个系列。请考虑以下数据框:
A B b7 b6 b5 b4 b3 b2 b1 b0
0 190 1 0 0 0 0 0 0 0
1 700 1 0 0 0 0 0 0 1
2 540 1 0 0 0 0 0 1 1
我想遍历每一行并检查 b7:b0 中的值。如果值 1 ,则根据以下内容计算总和: sum =(1 * x ^( - position))。基于上面的例子,总和应该是:
1. 第一行:sum = 1 * x ^( - 7)
2. 第二行:sum = 1 * x ^( - 7)+ 1 * x ^( - 0)
3. 第三行:sum = 1 * x ^( - 7)+ 1 * x ^( - 1)+ 1 * x ^( - 0)
其中X是常数值。结果应添加到原始数据框:
A B b7 b6 b5 b4 b3 b2 b1 b0 Result
0 190 1 0 0 0 0 0 0 0 number
1 700 1 0 0 0 0 0 0 1 ..
2 540 1 0 0 0 0 0 1 1 ..
对于拆分和提取数据,我遵循两种方法(据我所知)是否使用子集或遵循经典的拆分方式。
# loop through the data-frame ( here number of records n=3)
# df is the data-frame
for (i in 1:3){
y<- df[i,3:10]
}
# the above code extracts one row for each iteration with columns from b7:b0. gives an output :
b7 b6 b5 b4 b3 b2 b1 b0
1 0 0 0 0 0 1 1
子集方法
# Subset the df into new data-frame which only contains the b7:b0
newDF<-subset.data.frame(df,select=b7:b0 )
我的问题是,如何遍历数据框,检查值并计算系列。我只想使用许多 IF 语句来检查每个值。我确信还有其他替代方法。
有什么建议吗?
答案 0 :(得分:3)
以下是poly()
和矩阵乘法的解决方案:
str <- "A,B,b7,b6,b5,b4,b3,b2,b1,b0
0,190,1,0,0,0,0,0,0,0
2,540,1,0,0,0,0,0,1,1
1,700,1,0,0,0,0,0,0,1"
file <- textConnection(str)
df <- read.table(file, header = T, sep = ",")
x <- 2
as.matrix(df[,3:10]) %*% rev(c(1, poly(x=1/x, degree=7, raw = TRUE)))
# > as.matrix(df[,3:10]) %*% rev(c(1, poly(x=1/x, degree=7, raw = TRUE)))
# [,1]
# [1,] 0.0078125
# [2,] 1.5078125
# [3,] 1.0078125
我使用了@ Wietze314答案中的数据定义 变体:
as.matrix(df[,9:3]) %*% t(poly(x=1/x, degree=7, raw = TRUE)) + df$b0
tcrossprod(as.matrix(df[,9:3]), poly(x=1/x, degree=7, raw = TRUE)) + df$b0
答案 1 :(得分:2)
您可以在apply()
函数中隐藏循环:
df <- read.table(text =
" A B b7 b6 b5 b4 b3 b2 b1 b0
0 190 1 0 0 0 0 0 0 0
1 700 1 0 0 0 0 0 0 1
2 540 1 0 0 0 0 0 1 1",
header = TRUE)
X <- 3
df$Result <- apply(df[, 3:10], 1, function(row) sum(row * X ^ (-7:-0)))
df
# A B b7 b6 b5 b4 b3 b2 b1 b0 Result
# 1 0 190 1 0 0 0 0 0 0 0 0.0004572474
# 2 1 700 1 0 0 0 0 0 0 1 1.0004572474
# 3 2 540 1 0 0 0 0 0 1 1 1.3337905807
编辑:来自@jogo的更好解决方案:
as.matrix(df[, 3:10]) %*% (1/X)^(7:0)
## [,1]
## [1,] 0.0004572474
## [2,] 1.0004572474
## [3,] 1.3337905807
答案 2 :(得分:2)
我认为您可以使用矢量计算和apply
执行此操作,如下所示
数据:
str <- "A,B,b7,b6,b5,b4,b3,b2,b1,b0
0,190,1,0,0,0,0,0,0,0
2,540,1,0,0,0,0,0,1,1
1,700,1,0,0,0,0,0,0,1"
file <- textConnection(str)
dat <- read.table(file, header = T, sep = ",")
x = 2
方法:
colSums(apply(dat[,3:10], 1, function(i) i*x^(-7:0)))
结果:
[1] 0.0078125 1.5078125 1.0078125