【问题标题】:Finding value that corresponds to same location in another matrix查找对应于另一个矩阵中相同位置的值
【发布时间】:2015-06-03 09:10:45
【问题描述】:

我正在尝试获取每个人的因子分数。因子存储在数据帧factors 中,我需要获取另一个名为data 的数据帧中与factors 对应的值的平均值,并将其存储在data 的新列中。我为糟糕的解释道歉。我希望我的例子会有所帮助,我很乐意回答问题!

factors<-data.frame(c(NA,2,NA),c(NA,3,1))
colnames(factors)<-c("v1","v2")
row.names(factors)<-c("col1data","col2data","col3data")
factors

data<-data.frame(c(2,4,2),c(1,1,2),c(3,3,3))
colnames(data)<-c("col1data","col2data","col3data")
row.names(data)<-c("person1","person2","person3")
data
#in dataframe factors row col2data is present (i.e. not NA) under factor V1
#go into dataframe data for each person and make a new column called v1 that holds the value of col2data
#do this for factor v2 and average the values to come up with one number for each person. Final result
data<-data.frame(c(2,4,2),c(1,1,2),c(3,3,3),c(1,1,2),c(2,3,2.5))
colnames(data)<-c("col1data","col2data","col3data","v1","v2(avg col2 and col3)")
row.names(data)<-c("person1","person2","person3")
data

我将尝试将其分解为几个步骤(据我了解该过程):

  • 在数据框factors 的列中查找非 NA 的行名
  • 将行名称与数据框data 列匹配。
  • data 中的匹配行名称求和,并将每个人存储在称为data 中列的列名称的新变量中(例如v1
  • 【问题讨论】:

      标签: r


      【解决方案1】:

      您可以将data 的行均值限制在适当的列中:

      cbind(data, apply(factors, 2, function(x) rowMeans(data[,!is.na(x),drop=FALSE])))
      #         col1data col2data col3data v1  v2
      # person1        2        1        3  1 2.0
      # person2        4        1        3  1 2.0
      # person3        2        2        3  2 2.5
      

      【讨论】:

      • lapply 可能更合适,您还可以通过索引为列表而不是列来摆脱drop=FALSE - cbind(data, lapply(factors, function(x) rowMeans(data[!is.na(x)])))
      【解决方案2】:

      我将您记下的方式放置在代码中作为 cmets 的过程,以查看过程中每个步骤的执行位置。

      factors<-data.frame(c(NA,2,NA),c(NA,3,1))
      colnames(factors)<-c("v1","v2")
      row.names(factors)<-c("col1data","col2data","col3data")
      factors
      
      data<-data.frame(c(2,4,2),c(1,1,2),c(3,3,3))
      colnames(data)<-c("col1data","col2data","col3data")
      row.names(data)<-c("person1","person2","person3")
      data
      
      #find row names in a column of dataframe factors that are not NA
      not_na_rows_v1 <- rownames(factors)[!is.na(factors$v1)]
      not_na_rows_v2 <- rownames(factors)[!is.na(factors$v2)]
      not_na_rows_v1
      not_na_rows_v2
      #match row names to dataframe data columns.
      #Sum matching row names in data and store in new variable called the column name of the column in data (eg v1) for each person
      ###*note*### apply(...,1 ,mean) takes the mean for each row (the "1" means by row, "2" would mean by column)
      data[, 'v1'] <- data[, not_na_rows_v1]
      data[, 'v2'] <- apply(data[, not_na_rows_v2], 1, mean)
      data
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多