【问题标题】:indexing a matrix in R在R中索引矩阵
【发布时间】:2012-05-28 11:01:50
【问题描述】:

这里是 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))

我想对特定月份的数据进行子集化,并对 temp 应用更改因子,然后保存结果。所以我有类似的东西

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

任何帮助将不胜感激。

【问题讨论】:

    标签: r matrix indexing


    【解决方案1】:

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

    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
    

    【讨论】:

    • 谢谢!正是我想要的。
    【解决方案2】:

    首先,请注意subset 不会生成索引,它会生成原始数据帧的子集,其中包含所有带有Month == 1 的行。

    然后,当您执行idx[,2] 时,您选择了Temp 列。

    results[idx[,2],1] = idx[,2] + change
    

    但是您将这些用作results索引,即您将它们用作行号。行号不能是10.56-1.11 之类的东西,因此您的错误。此外,您正在选择results 的第一列Date 并尝试为其添加温度。

    有几种方法可以做到这一点。

    您可以为具有Month == 1FALSE 的行创建逻辑索引TRUE,否则如下所示:

    idx <- datac1$Month == 1
    

    然后您可以使用该索引来选择您要修改的datac1 中的行(我认为这是您最初尝试做的):

    datac1$Temp[idx] <- datac1$Temp[idx] + change  # or 'results' instead of 'datac1'?
    

    注意datac1$Temp[idx] 选择datac1Temp 列和idx 行。

    你也可以

    datac1[idx,'Temp']
    

    datac1[idx,2]  # as Temp is the second column.
    

    如果您希望 results 成为 Month == 1 的子集,请尝试:

    results <- subset(datac1, Month == 1)
    results$Temp <- results$Temp + change
    

    这是因为results 只包含您感兴趣的行,因此无需进行子集设置。

    【讨论】:

    • 我很欣赏详细的解释。它帮助我准确了解发生了什么。谢谢
    【解决方案3】:

    就我个人而言,我会使用 ifelse() 并利用 within() 的语法美感来制作一个不错的单行符 datacl &lt;- within(datacl, Temp &lt;- ifelse(Month == 1, Temp + change,Temp))。好吧,我说的是一个班轮,但您还需要在其他地方定义 change

    【讨论】:

    • 还只是想提一下,您可以嵌套ifelse() 语句以考虑其他月份或条件。
    猜你喜欢
    • 2018-03-20
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多