我有一个这样的数据框:
dfin <- structure(list(stock = structure(1:3, .Label = c("stock1", "stock2",
"stock3"), class = "factor"), nameA = c(0.2, 0.3, 1.4), another = c(2L,
1L, 3L), thirdname = c(0L, 4L, 3L)), .Names = c("stock", "nameA",
"another", "thirdname"), class = "data.frame", row.names = c(NA,
-3L))
#> dfin
# stock nameA another thirdname
#1 stock1 0.2 2 0
#2 stock2 0.3 1 4
#3 stock3 1.4 3 3
我想计算每一行,将库存作为索引列,使用其他值的变量/列来计算这个类型:
typeA = nameA - another + thirdname
second = -nameA + another - thirdname
我想生成这样的输出数据框:
dfout <- structure(list(stock = structure(1:3, .Label = c("stock1", "stock2",
"stock3"), class = "factor"), typeA = structure(c(1L, 3L, 2L), .Label = c("-1,8",
"1,4", "3,3"), class = "factor"), second = structure(c(3L, 2L,
1L), .Label = c("-1,4", "-3,3", "1,8"), class = "factor")), .Names = c("stock",
"typeA", "second"), class = "data.frame", row.names = c(NA, -3L
))
> dfout
stock typeA second
1 stock1 -1,8 1,8
2 stock2 3,3 -3,3
3 stock3 1,4 -1,4
有没有简单的方法可以为数据帧的所有行创建它而无需使用for循环?
答案 0 :(得分:3)
使用基数R,您可以:
within(dfin, {
typeA = nameA - another + thirdname
second = -nameA + another - thirdname
rm(nameA, another, thirdname)
})
# stock second typeA
# 1 stock1 1.8 -1.8
# 2 stock2 -3.3 3.3
# 3 stock3 -1.4 1.4
使用tidyverse,你可以这样做:
library(tidyverse)
dfin %>%
mutate(typeA = nameA - another + thirdname,
second = -nameA + another - thirdname) %>%
select(-nameA, -another, -thirdname)
或根据评论中的建议transmute
:
dfin %>%
transmute(stock,
typeA = nameA - another + thirdname,
second = -nameA + another - thirdname)
使用“data.table”,例如:
library(data.table)
as.data.table(dfin)[, c("typeA", "second") := list(
nameA - another + thirdname,
-nameA + another - thirdname
)][, c("nameA", "another", "thirdname") := NULL][]