【问题标题】:Cleaning up Census Bureau data frames清理人口普查局数据框
【发布时间】:2015-04-13 21:20:42
【问题描述】:

我正在尝试清理和操作人口普查局数据的数据框。我在 R 中使用(for 循环)来做到这一点,但到目前为止这需要 20 多个小时!

问题是我使用了两个不同的数据框

这是我的代码

t=1
for(i in 1:25558){ # number of records in the Housing record

family <- array(0,dim=c(0,12)) # creating an empty array to store row number

k=1
n=0
for(j in t:52608){  # number of records in the Personal record
   if(Housing[i,5] == Personal[j,2]) {
     family[k]=j
     k=k+1
     n=1
     }
   else( 
    if(n == 1) {
      t=j
      break
     }
    )
}

a=0 
for(m in 1:length(family)){
    if(is.na(Personal[family[m],22])) {  # Some families has mix values: NA and numbers
      break
      }

 else( 
     if(Personal[family[m],22] > 1){
     a=a+1
     }
     )
  }

 if(a == length(family)) {
     Housing[i,1]=1
    }

}

(编辑 - 一个例子): 在 Hosing 记录中,我对每个家庭都有一个 ID。在个人记录中,所有家庭成员都使用相同的家庭 ID。

Housing Record:
ID  Family Ability to Speak English
1             0
2             0
3             1



Personal Record:
ID  Member  Person Ability to Speak English
1     1                    1
1     2                    NA
1     3                    2
2     1                    4
2     2                    1
3     1                    3
3     2                    2 

注意:这里的“NA”不代表“不可用”,它有特定的含义(基本上不应该去掉)

我需要根据家庭成员的英语口语能力将“家庭英语口语能力”列的值更改为 1。 (见我的代码的最后一部分)

【问题讨论】:

  • 请提供一些显示数据结构的示例,并描述“清理”后的输出应该是什么样子。
  • 你好,我举个例子,谢谢
  • 您能用文字解释一下您分配 0 而不是 1 的规则是什么?循环有很多移动部件,很难跟随。此外,Personal[family[m],22] 与您的示例中的任何内容都不匹配。
  • 您给定的数据并不清楚家庭能力列是如何确定的。家庭 2 有两个成员得分为正,但家庭能力列为零。

标签: r performance for-loop dataframe


【解决方案1】:
# some dummy data frame for families
family <- data.frame(famid=rep(1:5, each=3), 
                     member=rep(1:3, 5), 
                     speake=sample(c(1:4, NA, NA), 15, replace=TRUE))

# a function to calculate scores 
# (modify according to your scoring algorithm)
english_score <- function(fam){
    # pull out the English scores for all members of fam
    data <- family$speake[which(family$famid==fam)]
    # I dont know how you want to number the families,
    # by their combined English score, or just if any exist
    # so demonstrate both
    eng_sum <- sum(na.omit(data))
    eng_present <- !any(is.na(data))

    #return this result of the function as a vector
    c(fam, eng_sum, eng_present)
}

# apply the function to each unique family
housing <- sapply(unique(family$famid), english_score)
housing <- as.data.frame(t(housing))
colnames(housing) <- c("family", "eng_sum", "eng_present")

【讨论】:

  • 好吧,我写的不是“是英语礼物”而是“每个人都说英语吗”
  • 感谢您的帮助
  • 如果您使用复选标记选择此作为正确答案,那就太好了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-20
  • 1970-01-01
  • 2016-03-23
  • 2017-07-05
  • 2021-12-17
  • 2013-09-26
  • 1970-01-01
相关资源
最近更新 更多