创建数字序列以使组变量中的每个更改递增的有效方法是什么?作为一个玩具示例,使用下面的数据框,我希望一个新变量“ Value”采用值c(1,1,1,2,2,3,3,4)
。请注意,即使48重复,“ Value”仍然会增加,因为我只关心序列的更改。
df <- read.table(textConnection(
'Group
48
48
48
56
56
48
48
14'), header = TRUE)
一种方法是
df$Value<-1
for(i in 2:nrow(df)){
if(df[i,]$Group==df[i-1,]$Group){df[i,]$Value=df[i-1,]$Value}
else{df[i,]$Value=df[i-1,]$Value+1}
}
但这非常慢。我的实际数据集有几百万个观测值。
注意:我在输入此问题的标题时遇到了麻烦,请根据需要进行更改。
答案 0 :(得分:4)
我们还可以入侵user_email
。
temp_rotated_img = temp_img.rotate(rotation, center = image_center)
for i in range(len(new_points_x)):
rotated_x, rotated_y = rotate_around_point((new_points_x[i],
new_points_y[i]), math.radians(rotation),
origin = image_center)
rotated_image_points_x.append(rotated_x)
rotated_image_points_y.append(rotated_y)
数据
rle
答案 1 :(得分:0)
怎么样
library(tidyverse)
df = data.frame(Group = c(48,
48,
48,
56,
56,
48,
48,
14))
# Get unique values in group
unique_vals = unique(df$Group)
# create a sequence from 1 up until the length of the unique values vector
sequential_nums = 1:length(unique_vals)
# Create a new column looking up the current value in the unique_vals list
# and replacing it with the correct sequential number
df %>%
mutate(Value = sequential_nums[match(Group, unique_vals)])
# Group Value
# 1 48 1
# 2 48 1
# 3 48 1
# 4 56 2
# 5 56 2
# 6 48 1
# 7 48 1
# 8 14 3