R中的替换功能问题

时间:2017-01-20 08:20:09

标签: r vector replace

我有一个矢量:

> a <- c(0,1,2,3,4)

我正在尝试使用递增1的值替换所有值的值,如下所示:

a <- (1,2,3,4,5)
> replace(a,a==4,5)
[1] 0 1 2 3 5

但是当我尝试用4替换3时,存在一些问题

replace(a,a==3,4)
[1] 0 1 2 4 4

3和5都转换为4。

当我尝试用3代替2时,同样的情况发生了

> replace(a,a==2,3)
[1] 0 1 3 3 4

有人可以指出我在这里做错了吗?

1 个答案:

答案 0 :(得分:2)

> a = c(0,1,2,3,4) > replace(a,a==2,99) [1] 0 1 99 3 4 不会改变其论点。

a

但是> a [1] 0 1 2 3 4 仍然是相同的:

a

所以当你以为你在a中将4转换为5时你没有。如果要更改> a [1] 0 1 2 3 4 > a = replace(a,a==2,99) > a [1] 0 1 99 3 4

,请使用返回值
a=a+1

[正如评论中所指出的,有更好的方法可以为向量的所有值添加1,public void dibujarGrafica6Periodos(ExcelWorksheet ws, CultureInfo idioma) { CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; TextInfo textinfo = cultureInfo.TextInfo; var chart = ws.Drawings.AddChart("barChart2", OfficeOpenXml.Drawing.Chart.eChartType.BarClustered); chart.SetPosition(34, 0, 10, 10); chart.SetSize(940, 20*14); var serie1 = chart.Series.Add(ws.Cells["E36:E41"], ws.Cells["A36:A41"]); var serie2 =chart.Series.Add(ws.Cells["C36:C41"], ws.Cells["A36:A41"]); chart.Title.Text = "Consumo por Periodos - " + textinfo.ToUpper(DateTime.Now.ToString("MMMM", idioma)); chart.Title.Font.Color = System.Drawing.ColorTranslator.FromHtml("#4F81BD"); chart.Border.Fill.Style = eFillStyle.NoFill; chart.Title.Font.Size = 6; chart.YAxis.Font.Size = 5; chart.XAxis.Font.Size = 5; chart.Legend.Font.Size = 5; chart.Legend.Font.Color = System.Drawing.ColorTranslator.FromHtml("#4F81BD"); chart.YAxis.Font.Color = System.Drawing.ColorTranslator.FromHtml("#4F81BD"); chart.XAxis.Font.Color = System.Drawing.ColorTranslator.FromHtml("#4F81BD"); chart.Legend.Position = OfficeOpenXml.Drawing.Chart.eLegendPosition.Bottom; chart.Style = OfficeOpenXml.Drawing.Chart.eChartStyle.Style10; serie1.Header = DateTime.Now.ToString("yyyy"); serie2.Header = DateTime.Now.AddYears(-1).ToString("yyyy"); } 是最好的]