我正在try 构建一个测量跟踪器表单.我想根据各行的Quantity值将0填充到每行的"Measures"列中.(对于数量=2,前2个测量值=0,行的其余部分=NA).(对于数量=4,所有测量值=0).
我想知道如何改变这些行,并在正确索引的位置用适当数量的0替换,如下所示:
Feature Tool MIN MAX Quantity Measurement_1 Measurement_2 Measurement_3 Measurement_4
1 a m 0.5 1.0 2 0 0 NA NA
2 b n 0.4 1.2 4 0 0 0 0
生成数据帧的示例代码如下所示:
#sample data
A1 <- data.frame(Feature = c("a","b"), Tool = c("m","n"), MIN = c(0.5,0.4), MAX = c(1.0,1.2), Quantity = c(2,4))
# Create empty data frame of NA
df <- data.frame(matrix(NA,
nrow = 1,
ncol = max(A1$Quantity)))
#create list of sequential measurements based on maximum quantity of measurements
M <- c(sprintf("Measurement_%01d", seq(1,max(A1$Quantity))))
#set column names to these measurements
colnames(df) <- M
#combine sample data with measurements
new_dat <- cbind(A1, df)
我第一次try 做到这一点是这样的:
new_dat %>% rowwise() %>% mutate(new_dat[,6:new_dat$Quantity] <- 0)
但很明显我漏掉了一些东西.
谢谢!