if语句错误,我遗漏了一些简单的东西

时间:2014-02-27 23:30:41

标签: r if-statement

G'day Everyone,

我真的很抱歉我来这里遇到这个问题,但我遗漏了一些非常基本的东西。我从here下载了ascii文件。我已经将这些数据设置为仅包含我感兴趣的列和行。现在我要做的就是用长格式状态名称替换短“状态”名称。我需要长格式的州名来输入我写的另一个函数。

如果您无法下载文件,我会尝试大致重现data.frame。

    # If data file was downloaded.
    gazet <-   read.table('file location', sep = ',')
    gazet <- gazet[,c(2:6, 8, 10, 14)]
    colnames(gazet) <- c('recID', 'authID', 'state', 'name', 'feature',
                         'postcode', 'lon', 'lat')

    towns <- gazet[which(gazet$feature %in% c('LOCB', 'SUB', 'URBN', 'POPL')
                 & !gazet$state %in% c('JBT', 'NFK', 'MCD', 'HRD', 'AAT', 'N/A')),]

    # If you don't want to download the file.
    towns <- data.frame('recID' = c('G62', 'G63', 'G64'), 
                        'state' = c('QLD', 'SA', 'VIC'),
                        'name'  = c('Balgal Beach', 'Balhannah', 'Ballan'),
                        'feature' = c('POPL', 'POPL', 'POPL'))

    # Using whichever towns you prefer, first I change state to character
    # so that it can be changed.
    towns$state <- as.character(towns$state)

    state_longform <- function(x){
      for (i in 1:length(x$state)){
        if (x[i, 'state'] == 'VIC'){
           x[i, 'state'] <- 'Victoria'
        } else{ x[i, 'state'] == 'NA'}
      }
    } 

    state_longform(towns)
    head(towns)

我的功能不起作用,但如果我在功能之外执行每个组件。

    towns[1, 'state'] == 'VIC'
    towns[3, 'state'] == 'VIC'

    towns[3, 'state'] <- 'Victoria'

我计划完整的功能会将所有状态名称更改为longform(例如'QLD'到'Queensland'等),但我开始使用较短的函数来确保它有效。它没有: - (。

我确信有一些真的很愚蠢,我很遗憾,我很抱歉,但我很久没有去过任何地方了。如果你知道自己是个白痴,或者是否有更好的地方可以解决这类简单问题,那么stackoverflow是否适合提问?

非常感谢您的帮助。

此致 亚当

2 个答案:

答案 0 :(得分:2)

您需要从函数中返回更改的值。

state_longform <- function(x){
  for (i in 1:length(x$state)){
    if (x[i, 'state'] == 'VIC'){
       x[i, 'state'] <- 'Victoria'
    } else{ x[i, 'state'] == 'NA'}
  }
  return(x)
} 

您也可以在该行上仅使用return(x)替换x,该函数将返回该值,但我认为explicate返回使代码更具可读性。

答案 1 :(得分:1)

你可以这样做吗?

towns[towns$state == "VIC", ]$state <- "Victoria"

如果要将所有短名称与长名称交换,请执行以下操作,但请确保longsshorts向量中相应的长名称和短名称的索引相同:< / p>

longs <- c("Victoria", "Queensland", "New South Wales", "South Australia")
shorts <- c("VIC", "QLD", "NSW", "SA")
towns$state <- longs[match(towns$state, shorts)]

> head(towns)
      recID authID           state         name feature postcode      lon
33704   G62     GA      Queensland Balgal Beach    POPL     4816 146.4083
33705   G63     GA South Australia    Balhannah    POPL     5242 138.8257
33706   G64     GA        Victoria       Ballan    POPL     3342 144.2289
33707   G65     GA        Victoria     Ballarat    POPL     3353 143.8626
33708   G66     GA New South Wales      Ballina    POPL     2478 153.5654
33709   G67     GA New South Wales    Balranald    POPL     2715 143.5633
相关问题