You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DataFrame内计算报错:非数值参数,求指定行计算并新增列的方法

Hey there! The issue you're hitting is because your max_L and max_W columns are stored as character strings (note the commas used as decimal separators) instead of numeric values—R can't do arithmetic on text, hence the "non-numeric argument" error. Let's fix this step by step:

1. Base R Solution

First, we'll convert the comma-separated string columns to numeric values by replacing commas with dots, then calculate your desired new column:

# Convert character columns to numeric
mydata$max_L <- as.numeric(gsub(",", ".", mydata$max_L))
mydata$max_W <- as.numeric(gsub(",", ".", mydata$max_W))

# Calculate the new column (name it whatever you like, e.g. total_inverse)
mydata$total_inverse <- 1/mydata$max_L + 1/mydata$max_W

2. Tidyverse Solution (dplyr + readr)

If you prefer a more streamlined workflow with the tidyverse, this method handles the decimal separator conversion cleanly without modifying columns manually:

library(dplyr)
library(readr)

mydata <- mydata %>%
  mutate(
    # Parse strings to numeric, recognizing commas as decimal marks
    max_L = parse_number(max_L, locale = locale(decimal_mark = ",")),
    max_W = parse_number(max_W, locale = locale(decimal_mark = ",")),
    # Compute the inverse sum
    total_inverse = 1/max_L + 1/max_W
  )

Result Preview

After running either method, your mydata will look like this (rounded for readability):

max_L max_W total_inverse
1  1.71  2.24       1.0208
2  1.44  3.14       0.9736
3  2.35  1.67       1.1054
4  1.64  2.50       0.9135
5  3.00  1.57       0.9929
6  1.73  2.22       1.0121

内容的提问来源于stack exchange,提问作者TheBeginner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:07:40