编辑列表元素

时间:2016-12-22 20:26:18

标签: r

我有一个数据框df,我分成一个大的列表,现在我想根据值(numtake)更改列表的元素,所以对于下面的例子中的每个列表元素我会如果numtake = 1,则将第一行的Init值更改为“new”,如果numtake = 2等,则将前两行的Init值更改为

 $TH.9990.1
           Init Monthly  Dlr Cls.Accoun Cur.Balance  meandiff numtake
12920        TH       1 9990 502-******     3949.85  48.30333       1
12921        TH       1 9990 502-******      4112.69 211.14333       1
12922        TH       1 9990 502-******     3642.10 259.44667       1

$VAF.9990.1
           init Monthly  Dlr Cls.Accoun Cur.Balance  meandiff numtake
13834       VAF       1 9990 502-******     2600.24   78.7925       2
13835       VAF       1 9990 502-******      3618.78  939.7475      2
13836       VAF       1 9990 502-******     4337.44 1658.4075       2
13837       VAF       1 9990 502-******      159.67 2519.3625       2

感谢adavnce!

1 个答案:

答案 0 :(得分:0)

我认为这个基础R解决方案应该可行:

lapply(myList, function(x) within(x, Init[seq_len(numtake[1])] <- rep("new", numtake[1])))

$TH.9990.1
      Init Monthly  Dlr Cls.Accoun Cur.Balance  meandiff numtake       val
12920  new       1 9990 502-******     3949.85  48.30333       1 TH.9990.1
12921   TH       1 9990 502-******     4112.69 211.14333       1 TH.9990.1
12922   TH       1 9990 502-******     3642.10 259.44667       1 TH.9990.1

$VAF.9990.1
      Init Monthly  Dlr Cls.Accoun Cur.Balance  meandiff numtake        val
13834  new       1 9990 502-******     2600.24   78.7925       2 VAF.9990.1
13835  new       1 9990 502-******     3618.78  939.7475       2 VAF.9990.1
13836  VAF       1 9990 502-******     4337.44 1658.4075       2 VAF.9990.1
13837  VAF       1 9990 502-******      159.67 2519.3625       2 VAF.9990.1

第一次观察numtake用于选择赋值中重复的“new”值的数量以及seq_len的参数,以选择用于Init变量中的替换的元素值。 within减少了输入并将更改后的data.frame和lapply循环返回到列表中。

数据

structure(list(TH.9990.1 = structure(list(Init = c("TH", "TH", 
"TH"), Monthly = c(1L, 1L, 1L), Dlr = c(9990L, 9990L, 9990L), 
    Cls.Accoun = c("502-******", "502-******", "502-******"), 
    Cur.Balance = c(3949.85, 4112.69, 3642.1), meandiff = c(48.30333, 
    211.14333, 259.44667), numtake = c(1L, 1L, 1L), val = c("TH.9990.1", 
    "TH.9990.1", "TH.9990.1")), .Names = c("Init", "Monthly", 
"Dlr", "Cls.Accoun", "Cur.Balance", "meandiff", "numtake", "val"
), row.names = c("12920", "12921", "12922"), class = "data.frame"), 
    VAF.9990.1 = structure(list(Init = c("VAF", "VAF", "VAF", 
    "VAF"), Monthly = c(1L, 1L, 1L, 1L), Dlr = c(9990L, 9990L, 
    9990L, 9990L), Cls.Accoun = c("502-******", "502-******", 
    "502-******", "502-******"), Cur.Balance = c(2600.24, 3618.78, 
    4337.44, 159.67), meandiff = c(78.7925, 939.7475, 1658.4075, 
    2519.3625), numtake = c(2L, 2L, 2L, 2L), val = c("VAF.9990.1", 
    "VAF.9990.1", "VAF.9990.1", "VAF.9990.1")), .Names = c("Init", 
    "Monthly", "Dlr", "Cls.Accoun", "Cur.Balance", "meandiff", 
    "numtake", "val"), row.names = c("13834", "13835", "13836", 
    "13837"), class = "data.frame")), .Names = c("TH.9990.1", 
"VAF.9990.1"))