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

请求编写R语言代码:将数据框中重量统一转换为千克

Hey there! Let's solve this unit conversion problem in R—turning all weights into Kilograms and standardizing the Units column. Here are two practical approaches you can use:

Base R Solution (No Extra Packages Needed)

If you prefer sticking to base R without installing additional libraries, this quick method works perfectly:

# Create your sample data frame
x <- data.frame("SN" = 1:3, "weights" = c(2.1, 1500, 2500), "Units" = c("Kilograms", "Grams", "Grams"))

# Convert grams to kilograms and update the weights column
x$weights <- ifelse(x$Units == "Grams", x$weights / 1000, x$weights)

# Standardize the Units column to "Kilograms"
x$Units <- "Kilograms"

# Check the result
print(x)

How it works:

  • ifelse() checks each row: if Units is "Grams", it divides the weight by 1000 to convert to kilograms; otherwise, it keeps the original value (since those are already in kilograms).
  • We then overwrite the entire Units column to "Kilograms" to keep everything consistent.

Tidyverse/Dplyr Solution (Clean, Readable Code)

If you're using the tidyverse ecosystem, dplyr makes this task even more readable—especially if you might need to add more unit conversions later:

library(dplyr)

# Start with your sample data and transform it
x <- data.frame("SN" = 1:3, "weights" = c(2.1, 1500, 2500), "Units" = c("Kilograms", "Grams", "Grams")) %>%
  mutate(
    # Convert weights based on unit type
    weights = case_when(
      Units == "Grams" ~ weights / 1000,
      TRUE ~ weights  # Keep values as-is for any other units (here, just Kilograms)
    ),
    # Set all entries in Units to "Kilograms"
    Units = "Kilograms"
  )

# View the final data frame
x

Bonus: Scaling for More Units

If you ever need to handle additional units (like pounds, ounces, etc.), you can easily extend the case_when() logic. For example, to convert pounds to kilograms (1 pound ≈ 0.453592 kg):

x <- x %>%
  mutate(
    weights = case_when(
      Units == "Grams" ~ weights / 1000,
      Units == "Pounds" ~ weights * 0.453592,
      TRUE ~ weights
    ),
    Units = "Kilograms"
  )

Both methods will give you exactly the output you're looking for:

SN weights      Units
1  1     2.1 Kilograms
2  2     1.5 Kilograms
3  3     2.5 Kilograms

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 00:07:36