【问题标题】:Looping through data frames and add new columns with values based on part of data frame name in R循环遍历数据框并根据 R 中的部分数据框名称添加具有值的新列
【发布时间】:2017-06-01 11:02:53
【问题描述】:

我有几个这样命名的数据框:gkz.01.1999、gkz.01.2000...、gkz.02.1999、gkz.02.2000... 数据如下所示:

         col1  col2  col3  col4
1 under 1 year 14091 13394 27485
2       1 year 14476 13802 28278
3      2 years 15420 14336 29756
4      3 years 15285 14437 29722
5      4 years 14704 13901 28605
6      5 years 14966 14016 28982

如何遍历所有数据框(或使用应用)并向每个数据框添加两个新列,其中第一个新列 (gkz) 的值等于数据框名称的前两位数字,并且第二个新列(年份)中的值是否等于数据框名称的最后 4 位?例如,对于数据帧 gkz.01.1999:

         col1  col2  col3  col4   gkz     year
1 under 1 year 14091 13394 27485  01      1999
2       1 year 14476 13802 28278  01      1999
3      2 years 15420 14336 29756  01      1999
4      3 years 15285 14437 29722  01      1999
5      4 years 14704 13901 28605  01      1999
6      5 years 14966 14016 28982  01      1999

提前致谢。

【问题讨论】:

    标签: r loops dataframe lapply


    【解决方案1】:

    我们将data.frames 转换为list

    #get the objects that start with 'gkz' as strings
    nm1 <- ls(pattern = "gkz\\.\\d+")
    #use mget to get the values of the objects in a list
    lst <- mget(nm1)
    #extract the numbers that follow the gkz using sub
    nm2 <- sub("^[^.]+\\.([^.]+).*", "\\1", nm1)
    #extract the last 4 numbers with sub
    nm3 <- sub(".*\\.(\\d+)$", "\\1", nm1)
    
    #create new columns in the list of data.frame with Map
    lst1 <- Map(cbind, lst, gkz = nm2, year = as.integer(nm3))
    

    【讨论】:

    • 哪里有很好的资源来描述如何解释/使用所有这些鸡划痕? :)
    • @akaDrHouse 谢谢,我忘了。现在,更新了
    • 谢谢@akrun。这很有帮助。我实际上对您可以推荐的在线手册非常感兴趣。我看到这些在答案中一直使用,但在大多数情况下,它们对我来说仍然是希腊语。
    • @akaDrHouse 如果您正在寻找正则表达式,那么regular-expressions.info/tutorial.html 是一种选择
    • 这很好用。我曾尝试创建一个列表,然后使用 sub,但无法让它工作。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多