【问题标题】:R equivalent of python's loc functionalityR 等效于 python 的 loc 功能
【发布时间】:2021-12-29 09:58:26
【问题描述】:

我想在 R 数据框中设置一行的值。在python中我会去

df.loc[2050,"Column1"] = 33

以某种方式在 R 中尝试这样做是向数据框添加大量行。这是我的代码。

year_series <- c(2020,2030,2040,2050)
dfplot = data.frame(matrix(ncol = 1, nrow = 4))
colnames(dfplot) <- c("Column1")
rownames(dfplot) <- year_series
dfplot[2050,"Column1"] <- 33

【问题讨论】:

  • dfplot[ rownames(dfplot) == 2050 ,"Column1"] &lt;- 33
  • 在您的示例中,该数字指的是 2050 年代的行。或者尝试dfplot["2050","Column1"] &lt;- 33,因为class(rownames(dfplot))字符
  • 谢谢@maydin 和@Andre!两种方法都有效。

标签: python r


【解决方案1】:

您遇到的问题是您引用的是索引 2050,而不是名称为“2050”的行。这就是为什么您会看到添加了这么多行(准确地说是多达 2,050 行)。您要做的是引用行名“2050”

如果您运行,通过代码/输出说明这一点:

dfplot$Column1[2050] <- 33

你会收到错误:

Error in `$<-.data.frame`(`*tmp*`, Column1, value = c(NA, NA, NA, 33,  : 
  replacement has 2050 rows, data has 4

这是一个有用的错误代码。以下代码应该运行并为您提供所需的数据框:

year_series <- c(2020,2030,2040,2050)
dfplot = data.frame(matrix(ncol = 1, nrow = 4))
colnames(dfplot) <- c("Column1")
rownames(dfplot) <- year_series
dfplot["2050","Column1"] <- 33

如果您不重命名行,以后添加数据可能会更清晰、更容易。以这种方式运行它:

year_df <- data.frame(year = c(2020,2030,2040,2050))
year_df$Column1 <- 'NA'
year_df[year_df$year == 2050,"Column1"] <- 33 #in this case year is a number and not a string

【讨论】:

    猜你喜欢
    • 2020-09-07
    • 2010-11-28
    • 2017-03-07
    • 2020-12-30
    • 2014-04-21
    • 2015-08-04
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    相关资源
    最近更新 更多