【发布时间】:2021-11-27 01:23:21
【问题描述】:
我需要编写一个for循环来计算年份变量(例如var1874)*价格变量(例如num1874)的乘积,为每年创建一个新变量及其对应的价格值(例如newvar1874)。
A tibble: 4 x 7
cty var1874 var1875 var1876 num1874 num1875 num1876
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 0.78 0.83 0.99 2.64 2.8 3.1
2 2 0.69 0.69 0.89 2.3 2.3 2.58
3 3 0.42 0.48 0.59 2.28 2.44 2.64
4 4 0.82 0.94 1.09 2.28 2.36 3
# Here's the code I have so far...
var.num_ <- dim(mydata)[2]
for(i in 1:length(vars)) {
mydata[, var.num + i] <- recode(mydata[, vars[i]], "newvar")
names(mydata)[var.num + i] <- paste0("newvar", vars[i])
}
# This code generates new variables, but they all have NA values.
# I also get this error message:
Unreplaced values treated as NA as .x is not compatible.
Please specify replacements exhaustively or supply .default
# Does anyone have any tips or general suggestions on how to use
# a for loop to multiply variables and create new product variables?
【问题讨论】:
-
只要做 newvar1874
-
我将如何使用 for 循环来做到这一点?
-
在 R 中,星号 (*) 用于逐元素乘法。这是同一行中的元素相乘的地方。
标签: r