【问题标题】:How to multiply a single column in a data.frame by a number如何将 data.frame 中的单列乘以数字
【发布时间】:2021-10-24 02:27:59
【问题描述】:

我想知道如何将我使用脚本读取的 txt 文件中的单列乘以 5。我只知道如何将所有列乘以一个数字,而不是一列。 这是我读取txt文件的脚本:

d = read.table(file="tst1.txt",header=TRUE)

【问题讨论】:

    标签: r


    【解决方案1】:

    假设您的数据框d 有一个名为“数字”的列(您可以使用str(d) 查看数据框中列的实际名称)。要将列“数字”乘以 5,请使用:

    # You are referring to the column "number" within the dataframe "d"
    d$number * 5
    
    # The last command only shoes the multiplication.
    
    # If you want to replace the original values, use
    d$number <- d$number * 5
    
    # If you want to save the new values in a new column, use
    d$numberX5 <- d$number * 5
    

    另外,请尝试参考标准 R 文档,您可以在 official page 中找到该文档。

    【讨论】:

      【解决方案2】:

      d[,i]&lt;-d[,i]*5。有关提取部分对象的更多信息,请参阅?Extract

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-17
        • 2018-04-22
        • 2012-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-07
        相关资源
        最近更新 更多