根据列位置替换 NA

问题描述 投票:0回答:1

我有这张桌子

我希望第 2:6 栏中的 NA 为“Ag”,第 7:12 栏中的 NA 为“Non-Ag”。我正在考虑这样处理:如果 NA 并且在 2 和 6 之间的列中,则为“Ag”,否则为“Non-Ag”,但不断遇到错误。

输出为:

structure(list(X1 = c("Treatment", NA, "Long Term Arm", NA, "Short Term Arm", 
NA), X2 = c(NA, "# Ent.", "4.36", "[2.93]", "0.49", "[2.6]"), 
    X3 = c(NA, "Rev.", "8521.72", "[5523.36]", "10174.38∗∗", 
    "[5136.73]"), X4 = c("Ag", "Costs", "5277.01", "[3785.31]", 
    "5966.48∗", "[3464.9]"), X5 = c(NA, "Net-Rev.", "2137.42", 
    "[4615.71]", "4368.46", "[4033.6]"), X6 = c(NA, "Assets", 
    "29779.09∗∗∗", "[10833.07]", "15558.74∗", "[8977.02]"
    ), X7 = c(NA, "# Ent.", "5.57∗∗∗", "[1.81]", "2.90∗∗", 
    "[1.35]"), X8 = c(NA, "Rev.", "52857.68∗∗", "[22776.31]", 
    "13003.09", "[14778.92]"), X9A = c("Non-Ag", "Costs", "26778.28∗", 
    "[15747.31]", "2530.93", "[9819.96]"), X9B = c(NA, "Net-Rev.", 
    "26088.63∗∗", "[11245.63]", "10456.25", "[6713.02]"), 
    X12 = c(NA, "Assets", "6271.58", "[6082.45]", "883.07", "[4328.38]"
    )), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
))
r replace position row na
1个回答
0
投票

我将使用

is.na
根据缺少的值进行子集化,并为清楚起见分别分配“Ag”或“Non-Ag”。这还假设您要替换第 1 行中的
NA

df[1, 2:6][is.na(df[1, 2:6])] <- "Ag"
df[1, 7:12][is.na(df[1, 7:12])] <- "Non-Ag"
© www.soinside.com 2019 - 2024. All rights reserved.