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

