2017-02-17 50 views
1

我在R學習for loop。我試圖找出如何在data.frame的特定variable中製作for loop。我看了幾個例子在計算器中,例如Q1,Q2,Q3,但沒有一個對我所尋找的是有用的!如何在data.fame中爲變量執行for-loop?

作爲使用mtcars數據集的例子,讓我們說,我想執行for loop到:

的面貌邁向cyl,並定義cyl 4,6,8,寫,並以stringslow, medium, high),分別。

for (i in mtcars$cyl) { 
    if (mtcars$cyl == 4){ 
    print("low")} 
    if (mtcars$cyl == 6) { 
    print ("medium")} 
    if (mtcars$cyl == 8) { 
    print ("high")} 
    } 

當然,情況並非如此!

什麼期望是這樣的:

    mpg cyl disp hp drat wt qsec vs am gear carb 
Mazda RX4   21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 
Mazda RX4 Wag  21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 
Datsun 710  22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 
Valiant   18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 

皈依:

    mpg cyl  disp hp drat wt qsec vs am gear carb 
Mazda RX4   21.0 medium 160 110 3.90 2.620 16.46 0 1 4 4 
Mazda RX4 Wag  21.0 medium 160 110 3.90 2.875 17.02 0 1 4 4 
Datsun 710  22.8 low  108 93 3.85 2.320 18.61 1 1 4 1 
Hornet 4 Drive 21.4 medium 258 110 3.08 3.215 19.44 1 0 3 1 
Hornet Sportabout 18.7 high  360 175 3.15 3.440 17.02 0 0 3 2 
Valiant   18.1 medium 225 105 2.76 3.460 20.22 1 0 3 1 

解釋任何幫助,不勝感激!

+3

無需循環:'mtcars $ NEWCOL < - 因子(mtcars $團委,標籤= C( 「低」,「中等「,」高「))'詳見'?factor'。 – Frank

+1

所以它通常傾向於儘可能地避免在R中出現循環。這就是爲什麼弗蘭克斯迴應和D.B.的答案的第一部分確實是更正確的解決方案。與其花時間使用循環,而循環速度較慢並最終變得複雜得多,可以考慮花時間學習數組函數,並對「應用」函數組感到滿意。當涉及到代碼的整潔和可讀性以及它們可能執行給定操作的速度時,它們是FAR優越的。 – SeldomSeenSlim

+0

@AronBoettcher非常感謝建設性的建議! – Daniel

回答

4

這個特殊的操作可能沒有循環。

df = mtcars 
df$cyl[df$cyl == 4] = "low" #Subset the cyl values equal to 4 and assign 'low' 
#Repeat for other values 

但對於運行循環,我會去這樣

df = mtcars 

for (i in 1:length(df$cyl)) { #Iterate over the length of df$cyl 
#You could also do "for (i in seq_along(df$cyl)" 
#Run "seq_along(df$cyl)" and "1:length(df$cyl)" to understand what values are being generated 
    if (df$cyl[i] == 4){ #Index df$cyl by [i]. If the ith value is 4, assign 'low' 
     df$cyl[i] = "low" 
    } 
    if (df$cyl[i] == 6) { 
     df$cyl[i] = "medium" 
    } 
    if (df$cyl[i] == 8) { 
     df$cyl[i] = "high" 
    } 
} 
+4

一件小事:在幫助初學者時,試着鼓勵像'for(我在seq_along(df $ cyl)'而不是'for(我在1:length(df $ cyl))'' – joran

+0

@joran,謝謝! –

+1

@db,非常感謝!:) – Daniel