【问题标题】:Can I create a tibble with 1 row and 11 columns in R from a data frame with 0 rows and 0 columns?我可以从具有 0 行和 0 列的数据框中创建一个在 R 中具有 1 行和 11 列的小标题吗?
【发布时间】:2021-05-18 03:08:22
【问题描述】:

我已经导入了一些 Twitter 数据,这些数据为我提供了一个包含每个用户的小标题的列表。每个 tibble 有 11 列和不同数量的行,具体取决于 Twitter 用户有多少列表。 如果 Twitter 用户没有列表,则将其列为 0 行 0 列的数据框(参见图片中的 [3])。我不想删除此类条目,而是将它们保留为没有列表的用户。

因此,我在考虑是否可以创建一个包含 11 列和 1 行的 tibble,其中每个单元格包含一个“99”。

如何将列表中的数据框更改为小标题?

非常感谢您的帮助!

【问题讨论】:

    标签: r dataframe twitter tibble


    【解决方案1】:

    你可以试试:

    #get index of dataframes that has 0 columns
    inds <- lengths(list_data_outlier) == 0
    #get column names from other dataframe which is not empty
    cols <- names(list_data_outlier[[which.max(!inds)]])
    #create an empty dataframe with data as 99 and 1 row
    empty_df <- data.frame(matrix(99, nrow = 1, ncol = length(cols), 
                           dimnames = list(NULL, cols)))
    #replace the dataframes with 0 columns with empty_df
    list_data_outlier[inds] <- replicate(sum(inds), empty_df, simplify = FALSE)
    

    【讨论】:

    • 这很有帮助!非常感谢。有什么方法可以创建小标题而不是数据框?
    • 使用empty_df &lt;- tibble(matrix(99, nrow = 1, ncol = length(cols), dimnames = list(NULL, cols)))
    • 谢谢!这给了我一个 1 行 1 列的小标题。我尝试了 2 个有效的步骤:empty_df &lt;- data.frame(matrix(99, nrow = 1, ncol = length(cols), dimnames = list(NULL, cols))) empty_df &lt;- tibble(empty_df)
    • 请原谅我一直在打扰您,但是您是否也知道如何将列类型从双精度更改为字符/整数/逻辑?谢谢!
    • 您可以将第一行用作empty_df,即empty_df &lt;- list_data_outlier[[which.max(!inds)]][1, ],而不是创建以99为值的数据框,但这将在每个空数据框中重复第一行。您可能想就此提出一个新问题。
    【解决方案2】:

    再次感谢@Ronak Shah! 这很好用:

    inds <- lengths(list_data_outlier) == 0
    empty_df <- list_data_outlier[[which.max(!inds)]][1, ]
    list_data_outlier[inds] <- replicate(sum(inds), empty_df, simplify = FALSE)
    

    但是我没有选择第一行,因此在 DF 中有错误的数据,我使用了第 50 行:

    empty_df <- list_data_outlier[[which.max(!inds)]][50, ]
    

    该数字取决于条目数 nrows + 1。 这样,您将获得一个包含 1 行和与列表其余部分相同数量和类型的列的 tibble,但不是用“错误”数据填充它,而是用 NAs 填充,这是我继续分析所需要的.

    【讨论】:

      猜你喜欢
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 2014-01-15
      • 2018-10-01
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多