我花了一整天的時間試圖熟悉r中的(for)循環函數,但是我沒有找到解決問題的方法。如何在r中循環?
我想爲27個國家執行以下計算,而不必一次又一次鍵入代碼。
percentageAT_leakingroof <- length(c11dep$hh040[c11dep$hh040==0 & c11dep$db020=="AT"])/length(c11dep$hh040[c11dep$db020=="AT"])
percentageBE_leakingroof <- length(c11dep$hh040[c11dep$hh040==0 & c11dep$db020=="BE"])/length(c11dep$hh040[c11dep$db020=="BE"])
是否可以編寫一個循環來計算以下27個級別的百分比? (並且也能夠正確地爲它們命名?「percentageAT_leakingroof」,「percentageAT_leakingroof」等)
levels <- c("AT", "BE", "BG", "CH", "CY", "CZ", "DE", "DK", "EE", "EL", "ES", "FI", "FR", "HU", "IT", "LT", "LU", "LV", "MT", "NL", "PL", "PT", "RO", "SE", "SI", "SK", "UK")
預先感謝您的幫助!
試着用'sapply/lapply'即'LST < - lapply(levels,function(x)length(c11dep $ hh040 [c11dep $ hh040 == 0&c11dep $ db020 == x])/ length(c11dep $ hh040 [c11dep $ db020 == x])); names(lst)< - paste0('percentage',levels,'_ leakingroof'); lst' – akrun
用'table'和'prop.table'可能會更容易些。一個可重複的例子將會有所幫助 – akrun