2016-10-18 25 views
0

我正在嘗試向我的數據框添加一個名爲Solvent的列,並將根據溶劑利用率返回yes或no,我已成功添加另一列獲取縣的數據,但我的溶劑代碼不起作用。我收到錯誤:「錯誤的SCC $ SCC.Level.One:$操作是原子向量無效」R基於原子矢量數據向列數據框添加列

NEI <- readRDS("summarySCC_PM25.rds") 
SCC <- readRDS("Source_Classification_Code.rds") 

library(ggplot2) 


form <- NEI[,c("fips","SCC", "Emissions")] 
LANEI <- form[form$fips=="06037",] 
OCNEI <- form[form$fips == "06059",] 
SBCNEI <- form[form$fips =="06071",] 

AllNEI<-rbind(rbind(LANEI,OCNEI), SBCNEI) 

GetCounty <-function (fips) 
{ 
    if (fips == "06037") 
    return ("Los Angeles") 
    else if (fips == "06059") 
    return ("Orange County") 
    if (fips == "06071") 
    return ("San Bernardino County") 

} 
chckSolv <- function (SCC) 
{ 

    if (SCC$SCC.Level.One == "Solvent Utilization") 
    return ("Yes") 
    else 
    return ("No") 
} 


CountyData <- sapply(AllNEI$fips, GetCounty) 
solventData <- sapply(AllNEI$SCC,chckSolv) 
AllNEI <-cbind (AllNEI, Solvent = solventData) 
AllNEI <- cbind(AllNEI, county = CountyData) 
+0

什麼是' 「Source_Classification_Code.rds」'結構? –

+0

我認爲問題在於你傳遞了一個單獨的向量到你的'chckSolv'函數,但是它看起來應該帶一個名爲'SCC.Level.One'的列。嘗試'solventData < - sapply(AllNEI,chckSolv)' –

+0

僅供參考,您可以考慮使用向量化函數,如'ifelse()'而不是'chckSolv'和'GetCounty'函數。它會更快,並且會實現相同的目標。 –

回答

1

考慮使用向量化的ifelse()。您以前的錯誤是由於引用了具有特定值的SCC.Level.On上的指定元素SCC

AllNEI$CountyData <- ifelse(AllNEI$fips == "06037", "Los Angeles", 
          ifelse(AllNEI$fips == "06059", "Orange County", 
            ifelse(AllNEIfips == "06071", "San Bernardino County", NA) 

AllNEI$SolventData <- ifelse(AllNEI$SCC == "Solvent Utilization", "Yes", "No") 

此外,還可以減少rbind操作:

AllNEI <- NEI[NEI$fips %in% c("06037", "06059", "06071"), c("fips", "SCC", "Emissions")] 
+0

這樣做了!謝謝! – MattCom

1

這個問題似乎正在使用SCC作爲參數名稱創建功能chckSolv,但隨後使用它來嘗試引用在您的腳本中全局定義的SCC數據框。您的功能不會使用全局定義的版本(因爲名稱SCC在您的功能中是本地定義的)

如果您將參數更改爲不同的名稱,它應該有效。試試這樣:

chckSolv <- function (vec) 
{ 

    if (vec == "Solvent Utilization") 
    return ("Yes") 
    else 
    return ("No") 
} 
+0

@MikeyMike這是真的,但要更明確,而不是混淆他的全局定義變量,改變參數名稱是個好主意。 –

相關問題