gpt4 book ai didi

r - 在 R 中索引矩阵

转载 作者:行者123 更新时间:2023-12-04 15:25:27 25 4
gpt4 key购买 nike

这里是 R 新手用户。所以我有一个格式如下的数据集:

    Date  Temp  Month
1-Jan-90 10.56 1
2-Jan-90 11.11 1
3-Jan-90 10.56 1
4-Jan-90 -1.67 1
5-Jan-90 0.56 1
6-Jan-90 10.56 1
7-Jan-90 12.78 1
8-Jan-90 -1.11 1
9-Jan-90 4.44 1
10-Jan-90 10.00 1

在 R 语法中:
datacl <- structure(list(Date = structure(1:10, .Label = c("1990/01/01", 
"1990/01/02", "1990/01/03", "1990/01/04", "1990/01/05", "1990/01/06",
"1990/01/07", "1990/01/08", "1990/01/09", "1990/01/10"), class = "factor"),
Temp = c(10.56, 11.11, 10.56, -1.67, 0.56, 10.56, 12.78,
-1.11, 4.44, 10), Month = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L)), .Names = c("Date", "Temp", "Month"), class = "data.frame", row.names = c(NA,
-10L))

我想对特定月份的数据进行子集化,并对温度应用更改因子,然后保存结果。所以我有类似的东西
idx <- subset(datacl, Month == 1)  # Index
results[idx[,2],1] = idx[,2]+change # change applied to only index values

但我不断收到类似的错误
Error in results[idx[, 2], 1] = idx[, 2] + change: 
only 0's may be mixed with negative subscripts

任何帮助,将不胜感激。

最佳答案

首先,给变化因子一个值:

change <- 1

现在,这是创建索引的方法:
# one approach to subsetting is to create a logical vector: 
jan.idx <- datacl$Month == 1

# alternatively the which function returns numeric indices:
jan.idx2 <- which(datacl$Month == 1)

如果你只想要一月份的数据子集,
jandata <- datacl[jan.idx,]
transformed.jandata <- transform(jandata, Temp = Temp + change)

要保留整个数据框,但只将变化因子添加到 Jan temps:
datacl$Temp[jan.idx] <- datacl$Temp[jan.idx] + change

关于r - 在 R 中索引矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10693824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com