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

基于已有数据为R的data.frame新增from/to列的技术咨询

Hey there! Let's figure out how to add those from and to columns to your data frame. The goal is to set from as the first value in each id group, and to as the last value in the same group. Here are two straightforward approaches you can use:

Using dplyr (tidyverse)

If you're using the tidyverse ecosystem, dplyr makes this super clean with grouping and mutation:

# Load the package first
library(dplyr)

df <- df %>%
  group_by(id) %>%
  mutate(
    from = first(value),
    to = last(value)
  ) %>%
  ungroup()

Using Base R

If you prefer not to load extra packages, base R's ave() function works perfectly here:

df$from <- ave(df$value, df$id, FUN = function(x) x[1])
df$to <- ave(df$value, df$id, FUN = function(x) x[length(x)])

Either way, running this code will give you exactly the output you're looking for:

id value from to
1  1     a    a  e
2  1     b    a  e
3  1     c    a  e
4  1     d    a  e
5  1     e    a  e
6  2     a    a  c
7  2     b    a  c
8  2     c    a  c

These are standard grouping operations in R, so you'll find plenty of similar examples in R community discussions for handling per-group summary values across rows.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:06:23